Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on May 31st, 2011  |  syntax: None  |  size: 1.85 KB  |  views: 168  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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.     void *mem;
  40.     int size;
  41.  
  42.     s = tcc_new();
  43.     if (!s) {
  44.         fprintf(stderr, "Could not create tcc state\n");
  45.         exit(1);
  46.     }
  47.  
  48.     /* if tcclib.h and libtcc1.a are not installed, where can we find them */
  49.     if (argc == 2 && !memcmp(argv[1], "lib_path=",9))
  50.         tcc_set_lib_path(s, argv[1]+9);
  51.  
  52.     /* MUST BE CALLED before any compilation */
  53.     tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
  54.  
  55.     if (tcc_compile_string(s, my_program) == -1)
  56.         return 1;
  57.  
  58.     /* as a test, we add a symbol that the compiled program can use.
  59.        You may also open a dll with tcc_add_dll() and use symbols from that */
  60.     tcc_add_symbol(s, "add", add);
  61.  
  62.     /* get needed size of the code */
  63.     size = tcc_relocate(s, NULL);
  64.     if (size == -1)
  65.         return 1;
  66.  
  67.     /* allocate memory and copy the code into it */
  68.     mem = malloc(size);
  69.     tcc_relocate(s, mem);
  70.  
  71.     /* get entry symbol */
  72.     func = tcc_get_symbol(s, "foo");
  73.     if (!func)
  74.         return 1;
  75.  
  76.     /* delete the state */
  77.     tcc_delete(s);
  78.  
  79.     /* run the code */
  80.     func(32);
  81.  
  82.     free(mem);
  83.     return 0;
  84. }