fixup! riscv: Implement large addend for global address
[tinycc.git] / tests / libtcc_test.c
blob1428b1eabfce25cc5e6b9855cc411634ed579c2b
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 "libtcc.h"
11 void handle_error(void *opaque, const char *msg)
13 fprintf(opaque, "%s\n", msg);
16 /* this function is called by the generated code */
17 int add(int a, int b)
19 return a + b;
22 /* this strinc is referenced by the generated code */
23 const char hello[] = "Hello World!";
25 char my_program[] =
26 "#include <tcclib.h>\n" /* include the "Simple libc header for TCC" */
27 "extern int add(int a, int b);\n"
28 "#ifdef _WIN32\n" /* dynamically linked data needs 'dllimport' */
29 " __attribute__((dllimport))\n"
30 "#endif\n"
31 "extern const char hello[];\n"
32 "int fib(int n)\n"
33 "{\n"
34 " if (n <= 2)\n"
35 " return 1;\n"
36 " else\n"
37 " return fib(n-1) + fib(n-2);\n"
38 "}\n"
39 "\n"
40 "int foo(int n)\n"
41 "{\n"
42 " printf(\"%s\\n\", hello);\n"
43 " printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
44 " printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
45 " return 0;\n"
46 "}\n";
48 int main(int argc, char **argv)
50 TCCState *s;
51 int i;
52 int (*func)(int);
54 s = tcc_new();
55 if (!s) {
56 fprintf(stderr, "Could not create tcc state\n");
57 exit(1);
60 /* set custom error/warning printer */
61 tcc_set_error_func(s, stderr, handle_error);
63 /* if tcclib.h and libtcc1.a are not installed, where can we find them */
64 for (i = 1; i < argc; ++i) {
65 char *a = argv[i];
66 if (a[0] == '-') {
67 if (a[1] == 'B')
68 tcc_set_lib_path(s, a+2);
69 else if (a[1] == 'I')
70 tcc_add_include_path(s, a+2);
71 else if (a[1] == 'L')
72 tcc_add_library_path(s, a+2);
76 /* MUST BE CALLED before any compilation */
77 tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
79 if (tcc_compile_string(s, my_program) == -1)
80 return 1;
82 /* as a test, we add symbols that the compiled program can use.
83 You may also open a dll with tcc_add_dll() and use symbols from that */
84 tcc_add_symbol(s, "add", add);
85 tcc_add_symbol(s, "hello", hello);
87 /* relocate the code */
88 if (tcc_relocate(s) < 0)
89 return 1;
91 /* get entry symbol */
92 func = tcc_get_symbol(s, "foo");
93 if (!func)
94 return 1;
96 /* run the code */
97 func(32);
99 /* delete the state */
100 tcc_delete(s);
102 return 0;