libtcc_test.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. #include "libtcc.h"
  10. /* this function is called by the generated code */
  11. int add(int a, int b)
  12. {
  13. return a + b;
  14. }
  15. char my_program[] =
  16. "int fib(int n)\n"
  17. "{\n"
  18. " if (n <= 2)\n"
  19. " return 1;\n"
  20. " else\n"
  21. " return fib(n-1) + fib(n-2);\n"
  22. "}\n"
  23. "\n"
  24. "int foo(int n)\n"
  25. "{\n"
  26. " printf(\"Hello World!\\n\");\n"
  27. " printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
  28. " printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
  29. " return 0;\n"
  30. "}\n";
  31. int main(int argc, char **argv)
  32. {
  33. TCCState *s;
  34. int (*func)(int);
  35. void *mem;
  36. int size;
  37. s = tcc_new();
  38. if (!s) {
  39. fprintf(stderr, "Could not create tcc state\n");
  40. exit(1);
  41. }
  42. /* if tcclib.h and libtcc1.a are not installed, where can we find them */
  43. if (argc == 2 && !memcmp(argv[1], "lib_path=",9))
  44. tcc_set_lib_path(s, argv[1]+9);
  45. /* MUST BE CALLED before any compilation */
  46. tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
  47. if (tcc_compile_string(s, my_program) == -1)
  48. return 1;
  49. /* as a test, we add a symbol that the compiled program can use.
  50. You may also open a dll with tcc_add_dll() and use symbols from that */
  51. tcc_add_symbol(s, "add", add);
  52. /* get needed size of the code */
  53. size = tcc_relocate(s, NULL);
  54. if (size == -1)
  55. return 1;
  56. /* allocate memory and copy the code into it */
  57. mem = malloc(size);
  58. tcc_relocate(s, mem);
  59. /* get entry symbol */
  60. func = tcc_get_symbol(s, "foo");
  61. if (!func)
  62. return 1;
  63. /* delete the state */
  64. tcc_delete(s);
  65. /* run the code */
  66. func(32);
  67. free(mem);
  68. return 0;
  69. }