Skip to content

Instantly share code, notes, and snippets.

@llandsmeer
Created March 9, 2020 20:38
Show Gist options
  • Save llandsmeer/3489603e5070ee8dbe75cdf1865a5ca9 to your computer and use it in GitHub Desktop.
Save llandsmeer/3489603e5070ee8dbe75cdf1865a5ca9 to your computer and use it in GitHub Desktop.
LibTCC demo - usage example for live c code compilation & execution
#include <stdio.h>
#include <stdlib.h>
#include <libtcc.h>
void callme(int x) {
printf("hello, %d\n", x);
}
void error_func(void * user, const char * msg) {
printf("TCC Error: %s\n", msg);
exit(1);
}
int main(int argc, char ** argv) {
int err;
TCCState * s = tcc_new();
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
tcc_compile_string(s, "void callme(int); int main() { callme(42); }");
tcc_set_error_func(s, 0, error_func);
tcc_add_symbol(s, "callme", callme);
tcc_run(s, argc, argv);
tcc_delete(s);
}
@pktCoder
Copy link

pktCoder commented Aug 8, 2023

Thanks llandsmeer for the example! It shows that it's possible to compile a code in run time and run it. Kind of being equivalent to the "eval" in some scripting languages.

Here is what I did to get it compiled and run (YMMV).

  1. Checked out the source code of tcc (link here),

  2. untar and build it with ./configure; make

  3. cd tcc-0.9.27

  4. sudo mkdir /usr/local/lib/tcc

  5. sudo cp libtcc*.c /usr/local/lib/tcc

  6. Compile the above example code (put in a file called testme.c)
    gcc -I . testme.c -L . -ltcc -ldl

  7. ./a.out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment