You cannot do what you are dreaming of.
Preprocessing is one of the earliest phase of the compiler (e.g. gcc
). And your TPS
looks like you want it to have the compilation behavior depends on runtime variable var
. Conceptually, the compiler is first preprocessing your source. You can use gcc -C -E
to get the preprocessed textual form.
At compilation time, a variable has a name and the compiler will find its location (but a variable does not have any value during compilation). At runtime, a variable has a location containing a value. Values don't exist at compilation time, so you can't use them in the preprocessing phase.
However, the preprocessing can be conditionnal, like
#if WANTPRINT
printf("a: %d\n", a);
#endif
and then you could pass (or not) the -DWANTPRINT=1
flag to the compiler.
You could code
int var;
int main() {
int a, b, c;
a=1;b=2;c=3;
if (var) {
printf("a: %d\n", a);
printf("b: %d\n", b);
printf("c: %d\n", c);
};
printf("++a: %d\n", ++a);
return 0;
}
BTW, perhaps you want to dynamically load some code at runtime? On Linux and most Posix systems you can call dlopen(3) and dlsym
. You could even generate some C code in some (temporary) file, fork a process to compile it to a shared object, and dlopen
that shared object, get a function pointer with dlsym
then call it... See also this answer.
FWIW, Common Lisp has a very powerful macro system and is able to "compile" at runtime, and to do arbitrary computations at "compile-time". Actually, SBCL may generate good machine code while running....
Addenda
Perhaps you want to customize the behavior of the GCC compiler itself. Then you might consider using MELT (a domain specific language to extend GCC). But GCC don't enable customization of its preprocessing yet (but mostly of its middle-end, working on internal GCC representations like Gimple)