libtcc: add support to be build as DLL
[tinycc.git] / libtcc_test.c
bloba602fb0f496a59778daa5bab4fd9cc8d9d6b923e
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>
8 #include <string.h>
10 #include "libtcc.h"
12 /* this function is called by the generated code */
13 int add(int a, int b)
15 return a + b;
18 char my_program[] =
19 "int fib(int n)\n"
20 "{\n"
21 " if (n <= 2)\n"
22 " return 1;\n"
23 " else\n"
24 " return fib(n-1) + fib(n-2);\n"
25 "}\n"
26 "\n"
27 "int foo(int n)\n"
28 "{\n"
29 " printf(\"Hello World!\\n\");\n"
30 " printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
31 " printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
32 " return 0;\n"
33 "}\n";
35 int main(int argc, char **argv)
37 TCCState *s;
38 int (*func)(int);
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 /* if tcclib.h and libtcc1.a are not installed, where can we find them */
49 if (argc == 2 && !memcmp(argv[1], "lib_path=",9))
50 tcc_set_lib_path(s, argv[1]+9);
52 /* MUST BE CALLED before any compilation */
53 tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
55 if (tcc_compile_string(s, my_program) == -1)
56 return 1;
58 /* as a test, we add a symbol that the compiled program can use.
59 You may also open a dll with tcc_add_dll() and use symbols from that */
60 tcc_add_symbol(s, "add", add);
62 /* get needed size of the code */
63 size = tcc_relocate(s, NULL);
64 if (size == -1)
65 return 1;
67 /* allocate memory and copy the code into it */
68 mem = malloc(size);
69 tcc_relocate(s, mem);
71 /* get entry symbol */
72 func = tcc_get_symbol(s, "foo");
73 if (!func)
74 return 1;
76 /* delete the state */
77 tcc_delete(s);
79 /* run the code */
80 func(32);
82 free(mem);
83 return 0;