libtcc_test.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. /* this strinc is referenced by the generated code */
  16. const char hello[] = "Hello World!";
  17. char my_program[] =
  18. "#include <tcclib.h>\n" /* include the "Simple libc header for TCC" */
  19. "extern int add(int a, int b);\n"
  20. "#ifdef _WIN32\n" /* dynamically linked data needs 'dllimport' */
  21. " __attribute__((dllimport))\n"
  22. "#endif\n"
  23. "extern const char hello[];\n"
  24. "int fib(int n)\n"
  25. "{\n"
  26. " if (n <= 2)\n"
  27. " return 1;\n"
  28. " else\n"
  29. " return fib(n-1) + fib(n-2);\n"
  30. "}\n"
  31. "\n"
  32. "int foo(int n)\n"
  33. "{\n"
  34. " printf(\"%s\\n\", hello);\n"
  35. " printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
  36. " printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
  37. " return 0;\n"
  38. "}\n";
  39. int main(int argc, char **argv)
  40. {
  41. TCCState *s;
  42. int i;
  43. int (*func)(int);
  44. s = tcc_new();
  45. if (!s) {
  46. fprintf(stderr, "Could not create tcc state\n");
  47. exit(1);
  48. }
  49. /* if tcclib.h and libtcc1.a are not installed, where can we find them */
  50. for (i = 1; i < argc; ++i) {
  51. char *a = argv[i];
  52. if (a[0] == '-') {
  53. if (a[1] == 'B')
  54. tcc_set_lib_path(s, a+2);
  55. else if (a[1] == 'I')
  56. tcc_add_include_path(s, a+2);
  57. else if (a[1] == 'L')
  58. tcc_add_library_path(s, a+2);
  59. }
  60. }
  61. /* MUST BE CALLED before any compilation */
  62. tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
  63. if (tcc_compile_string(s, my_program) == -1)
  64. return 1;
  65. /* as a test, we add symbols that the compiled program can use.
  66. You may also open a dll with tcc_add_dll() and use symbols from that */
  67. tcc_add_symbol(s, "add", add);
  68. tcc_add_symbol(s, "hello", hello);
  69. /* relocate the code */
  70. if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
  71. return 1;
  72. /* get entry symbol */
  73. func = tcc_get_symbol(s, "foo");
  74. if (!func)
  75. return 1;
  76. /* run the code */
  77. func(32);
  78. /* delete the state */
  79. tcc_delete(s);
  80. return 0;
  81. }