Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  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. "#include <tcclib.h>\n" /* include the "Simple libc header for TCC" */
  20. "extern int add(int a, int b);\n"
  21. "int fib(int n)\n"
  22. "{\n"
  23. "    if (n <= 2)\n"
  24. "        return 1;\n"
  25. "    else\n"
  26. "        return fib(n-1) + fib(n-2);\n"
  27. "}\n"
  28. "\n"
  29. "int foo(int n)\n"
  30. "{\n"
  31. "    printf(\"Hello World!\\n\");\n"
  32. "    printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
  33. "    printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
  34. "    return 0;\n"
  35. "}\n";
  36.  
  37. int main(int argc, char **argv)
  38. {
  39.     TCCState *s;
  40.     int i;
  41.     int (*func)(int);
  42.  
  43.     s = tcc_new();
  44.     if (!s) {
  45.         fprintf(stderr, "Could not create tcc state\n");
  46.         exit(1);
  47.     }
  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.  
  62.     /* MUST BE CALLED before any compilation */
  63.     tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
  64.  
  65.     if (tcc_compile_string(s, my_program) == -1)
  66.         return 1;
  67.  
  68.     /* as a test, we add a symbol that the compiled program can use.
  69.        You may also open a dll with tcc_add_dll() and use symbols from that */
  70.     tcc_add_symbol(s, "add", add);
  71.  
  72.     /* relocate the code */
  73.     if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
  74.         return 1;
  75.  
  76.     /* get entry symbol */
  77.     func = tcc_get_symbol(s, "foo");
  78.     if (!func)
  79.         return 1;
  80.  
  81.     /* run the code */
  82.     func(32);
  83.  
  84.     /* delete the state */
  85.     tcc_delete(s);
  86.  
  87.     return 0;
  88. }
  89.