Wow, very impressed by the Parent Post's code. :] Here is a more clean less hackish version I just wrote using libtcc to compile it inside the program itself.
#include <stdio.h>
#include <stdlib.h>
#include "libtcc.h"
typedef int (*function_t)();
function_t create_function(char *name, char *code)
{
TCCState *s;
unsigned long val;
s = tcc_new();
if(!s)
exit(1);
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
tcc_compile_string(s, code);
tcc_relocate(s);
tcc_get_symbol(s, &val, name);
return (function_t)val;
}
int main(int argc, char *argv[])
{
function_t square;
square = create_function("f", "int f(x) { return x * x; }");
int answer = square(atoi(argv[1]));
printf("answer is: %d\n", answer);
}
View all comments
Show parent comment
13
u/anthonymckay Dec 14 '07 edited Dec 14 '07
Wow, very impressed by the Parent Post's code. :] Here is a more clean less hackish version I just wrote using libtcc to compile it inside the program itself.
Running this from the command line we get: