Introduction to the libtcc library for dynamic C code generation
The libtcc library enables you to use TCC as a backend for dynamic code generation. It allows you to compile C code at runtime and execute it directly in memory.
#include "libtcc.h"int main() { TCCState *s; int (*func)(int); // Create compilation context s = tcc_new(); if (!s) return 1; // Set output type to memory tcc_set_output_type(s, TCC_OUTPUT_MEMORY); // Compile C code tcc_compile_string(s, "int add(int a, int b) { return a + b; }"); // Relocate code if (tcc_relocate(s) < 0) return 1; // Get function pointer func = tcc_get_symbol(s, "add"); // Call the compiled function int result = func(5, 3); // Returns 8 // Cleanup tcc_delete(s); return 0;}
The global TCC state is protected by semaphores for basic thread safety, but you should generally avoid using the same TCCState from multiple threads simultaneously. Create separate TCCState instances for concurrent compilation.
You can provide a custom memory allocator using tcc_set_realloc() before creating any TCCState instances. This affects all memory allocation performed by TCC.
By default, errors and warnings are printed to stderr. You can set a custom error handler with tcc_set_error_func() to integrate TCC’s diagnostics into your application’s logging or UI.