[279] | 1 | /*
|
---|
| 2 | * Simple Test program for libtcc
|
---|
| 3 | *
|
---|
| 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 |
|
---|
| 10 | #include "libtcc.h"
|
---|
| 11 |
|
---|
| 12 | /* this function is called by the generated code */
|
---|
| 13 | int add(int a, int b)
|
---|
| 14 | {
|
---|
| 15 | return a + b;
|
---|
| 16 | }
|
---|
| 17 |
|
---|
| 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";
|
---|
| 34 |
|
---|
| 35 | int main(int argc, char **argv)
|
---|
| 36 | {
|
---|
| 37 | TCCState *s;
|
---|
| 38 | int (*func)(int);
|
---|
| 39 |
|
---|
| 40 | s = tcc_new();
|
---|
| 41 | if (!s) {
|
---|
| 42 | fprintf(stderr, "Could not create tcc state\n");
|
---|
| 43 | exit(1);
|
---|
| 44 | }
|
---|
| 45 |
|
---|
| 46 | /* if tcclib.h and libtcc1.a are not installed, where can we find them */
|
---|
| 47 | if (argc == 2 && !memcmp(argv[1], "lib_path=",9))
|
---|
| 48 | tcc_set_lib_path(s, argv[1]+9);
|
---|
| 49 |
|
---|
| 50 | /* MUST BE CALLED before any compilation */
|
---|
| 51 | tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
|
---|
| 52 |
|
---|
| 53 | if (tcc_compile_string(s, my_program) == -1)
|
---|
| 54 | return 1;
|
---|
| 55 |
|
---|
| 56 | /* as a test, we add a symbol that the compiled program can use.
|
---|
| 57 | You may also open a dll with tcc_add_dll() and use symbols from that */
|
---|
| 58 | tcc_add_symbol(s, "add", add);
|
---|
| 59 |
|
---|
| 60 | /* relocate the code */
|
---|
| 61 | if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
|
---|
| 62 | return 1;
|
---|
| 63 |
|
---|
| 64 | /* get entry symbol */
|
---|
| 65 | func = tcc_get_symbol(s, "foo");
|
---|
| 66 | if (!func)
|
---|
| 67 | return 1;
|
---|
| 68 |
|
---|
| 69 | /* run the code */
|
---|
| 70 | func(32);
|
---|
| 71 |
|
---|
| 72 | /* delete the state */
|
---|
| 73 | tcc_delete(s);
|
---|
| 74 |
|
---|
| 75 | return 0;
|
---|
| 76 | }
|
---|