Skip to main content
After initializing a TCC compilation context, you can compile C source code from strings or files.

Compiling from strings

tcc_compile_string

Compiles a C source code string.
TCCState*
required
The compilation context.
const char*
required
Null-terminated string containing C source code.
int
Returns 0 on success, -1 on error.
Example:
You must call tcc_set_output_type() before calling tcc_compile_string().

Better error reporting with #line

For more specific error messages, prefix your code with a #line directive:

tcc_compile_string_file

Compiles a C source string and optionally writes it to a file for debugging.
TCCState*
required
The compilation context.
const char*
required
Null-terminated string containing C source code.
const char*
If debugging is enabled, the source will be written to this file.
int
Returns 0 on success, -1 on error.
Example:

Compiling from files

tcc_add_file

Adds a file to the compilation. The file can be:
  • C source file (.c, .h)
  • Assembly file (.s, .S)
  • Object file (.o)
  • Library (.a, .so, .dll)
  • Linker script
TCCState*
required
The compilation context.
const char*
required
Path to the file to compile or link.
int
Returns 0 on success, -1 on error.
Example:

Multiple compilation units

You can compile multiple source files together:

Dynamic compilation patterns

Compiling generated code

Incremental compilation

Template-based code generation

Compilation with includes

When compiling code that uses standard library headers:

Error handling during compilation

Best practices

  • Always check return values from tcc_compile_string() and tcc_add_file()
  • Use #line directives for better error messages when compiling generated code
  • Set up error handlers before compilation for better diagnostics
  • For large projects, consider compiling to object files first, then linking
  • When generating code, validate your templates to avoid syntax errors