tccgen: Allow struct init from struct
[tinycc.git] / tests / libtcc_test.c
blobd21c7fef0daba3df5ccaa24b2e844c3814e88c04
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>
9 #include <assert.h>
11 #include "libtcc.h"
13 void handle_error(void *opaque, const char *msg)
15 fprintf(opaque, "%s\n", msg);
18 /* this function is called by the generated code */
19 int add(int a, int b)
21 return a + b;
24 /* this strinc is referenced by the generated code */
25 const char hello[] = "Hello World!";
27 char my_program[] =
28 "#include <tcclib.h>\n" /* include the "Simple libc header for TCC" */
29 "extern int add(int a, int b);\n"
30 "#ifdef _WIN32\n" /* dynamically linked data needs 'dllimport' */
31 " __attribute__((dllimport))\n"
32 "#endif\n"
33 "extern const char hello[];\n"
34 "int fib(int n)\n"
35 "{\n"
36 " if (n <= 2)\n"
37 " return 1;\n"
38 " else\n"
39 " return fib(n-1) + fib(n-2);\n"
40 "}\n"
41 "\n"
42 "int foo(int n)\n"
43 "{\n"
44 " printf(\"%s\\n\", hello);\n"
45 " printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
46 " printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
47 " return 0;\n"
48 "}\n";
50 int main(int argc, char **argv)
52 TCCState *s;
53 int i;
54 int (*func)(int);
56 s = tcc_new();
57 if (!s) {
58 fprintf(stderr, "Could not create tcc state\n");
59 exit(1);
62 assert(tcc_get_error_func(s) == NULL);
63 assert(tcc_get_error_opaque(s) == NULL);
65 tcc_set_error_func(s, stderr, handle_error);
67 assert(tcc_get_error_func(s) == handle_error);
68 assert(tcc_get_error_opaque(s) == stderr);
70 /* if tcclib.h and libtcc1.a are not installed, where can we find them */
71 for (i = 1; i < argc; ++i) {
72 char *a = argv[i];
73 if (a[0] == '-') {
74 if (a[1] == 'B')
75 tcc_set_lib_path(s, a+2);
76 else if (a[1] == 'I')
77 tcc_add_include_path(s, a+2);
78 else if (a[1] == 'L')
79 tcc_add_library_path(s, a+2);
83 /* MUST BE CALLED before any compilation */
84 tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
86 if (tcc_compile_string(s, my_program) == -1)
87 return 1;
89 /* as a test, we add symbols that the compiled program can use.
90 You may also open a dll with tcc_add_dll() and use symbols from that */
91 tcc_add_symbol(s, "add", add);
92 tcc_add_symbol(s, "hello", hello);
94 /* relocate the code */
95 if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
96 return 1;
98 /* get entry symbol */
99 func = tcc_get_symbol(s, "foo");
100 if (!func)
101 return 1;
103 /* run the code */
104 func(32);
106 /* delete the state */
107 tcc_delete(s);
109 return 0;