Basic scripting
Using shebang
Add a shebang line at the start of your C source file to make it executable:hello.c
The shebang path may vary depending on where TCC is installed. Common paths are:
/usr/local/bin/tcc/usr/bin/tcc
which tcc to find the correct path on your system.Portable shebang
For better portability across different systems, useenv:
tcc in the PATH environment variable.
Command-line arguments
Accessing arguments
Script arguments are passed to themain() function:
script_args.c
Processing arguments
Here’s a practical example that processes file arguments:file_info.c
TCC options in shebang
Adding compiler options
You can include TCC options in the shebang line:Linking with libraries
Include library flags in the shebang:math_script.c
Complex options
For multiple options, quote them as a single argument:x11_script.c
Reading from stdin
TCC can execute C code from standard input:Using tcclib
TCC providestcclib.h, a minimal library header that includes commonly used functions without requiring standard headers:
tcclib.h provides:
- Standard I/O functions (
printf,fprintf,puts, etc.) - Memory functions (
malloc,free,memcpy, etc.) - String functions (
strlen,strcmp,strcpy, etc.) - Basic file operations (
fopen,fclose,fread, etc.)
Practical examples
File processing script
process_log.c
Text processing
word_count.c
System administration
disk_usage.c
Performance considerations
Compilation overhead
While TCC compiles very quickly, there is still a compilation step each time the script runs:- First run
- Subsequent runs
- Compiled executable
For scripts that run frequently, consider compiling them to avoid the compilation overhead, even though TCC is very fast.
When to use C scripts
C scripting with TCC is ideal for:- System programming tasks - Direct access to system calls and low-level APIs
- Performance-critical scripts - Faster execution than interpreted languages
- Existing C code reuse - Quickly test or run C code snippets
- Learning and prototyping - Rapid C development without build systems
- Simple text processing - Shell scripts or awk/sed are simpler
- Complex string manipulation - Higher-level languages have better string support
- Cross-platform portability - Requires TCC on target system
Custom stdin for scripts
Redirect stdin for the running script:read_stdin.c
Debugging scripts
Enable debug info and bounds checking:-g and -b, you get:
- Clear error messages with file and line numbers
- Bounds checking for arrays and pointers
- Stack traces on errors