fix a subtle x86-64 calling bug
[tinycc.git] / tests / libtcc_test.c
blob414cc9bf56202e3fd3ed40dcd530fff7d18e4622
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 "#include <stdio.h> // printf()\n"
20 "extern int add(int a, int b);\n"
21 "int fib(int n)\n"
22 "{\n"
23 " if (n <= 2)\n"
24 " return 1;\n"
25 " else\n"
26 " return fib(n-1) + fib(n-2);\n"
27 "}\n"
28 "\n"
29 "int foo(int n)\n"
30 "{\n"
31 " printf(\"Hello World!\\n\");\n"
32 " printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
33 " printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
34 " return 0;\n"
35 "}\n";
37 int main(int argc, char **argv)
39 TCCState *s;
40 int (*func)(int);
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 /* relocate the code */
63 if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
64 return 1;
66 /* get entry symbol */
67 func = tcc_get_symbol(s, "foo");
68 if (!func)
69 return 1;
71 /* run the code */
72 func(32);
74 /* delete the state */
75 tcc_delete(s);
77 return 0;