alternative int tcc_relocate(TCCState *s1, void *ptr);
[tinycc/k1w1.git] / libtcc_test.c
blob4c16902a7f4ac524afe7ac562277f4b3e6ab1b06
1 /*
2 * Simple Test program for libtcc
4 * libtcc can be useful to use tcc as a "backend" for a code generator.
5 */
6 #include <stdlib.h>
7 #include <stdio.h>
9 #include "libtcc.h"
11 /* this function is called by the generated code */
12 int add(int a, int b)
14 return a + b;
17 char my_program[] =
18 "int fib(int n)\n"
19 "{\n"
20 " if (n <= 2)\n"
21 " return 1;\n"
22 " else\n"
23 " return fib(n-1) + fib(n-2);\n"
24 "}\n"
25 "\n"
26 "int foo(int n)\n"
27 "{\n"
28 " printf(\"Hello World!\\n\");\n"
29 " printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
30 " printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
31 " return 0;\n"
32 "}\n";
34 int main(int argc, char **argv)
36 TCCState *s;
37 int (*func)(int);
38 unsigned long val;
39 void *mem;
40 int size;
42 s = tcc_new();
43 if (!s) {
44 fprintf(stderr, "Could not create tcc state\n");
45 exit(1);
48 /* MUST BE CALLED before any compilation or file loading */
49 tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
51 tcc_compile_string(s, my_program);
53 /* as a test, we add a symbol that the compiled program can be
54 linked with. You can have a similar result by opening a dll
55 with tcc_add_dll(() and using its symbols directly. */
56 tcc_add_symbol(s, "add", (unsigned long)&add);
58 /* get needed size of the code */
59 size = tcc_relocate(s, NULL);
60 if (size == -1)
61 return 1;
63 /* allocate memory and copy the code into it */
64 mem = malloc(size);
65 tcc_relocate(s, mem);
67 /* get entry symbol */
68 tcc_get_symbol(s, &val, "foo");
69 func = (void *)val;
71 /* delete the state */
72 tcc_delete(s);
74 /* run the code */
75 func(32);
77 free(mem);
78 return 0;