Suppose I have a some C code, say, printf("A"); how can I repeat it N number of times based on some compile time argument where N is passed in that compiler argument. e.g gcc -D print=N
Similarly, is there a way where we can pass the range of the loop based on the compile time argument/flag?
Simply put it into a loop:
for (int i = 0; i < print; ++i)
printf("A");
The print symbol will be substituted by the value specified on the compiler command line (e.g. -Dprint=5), so the loop runs the desired amount of times. You can do the same thing with the start value 0 by adding another -D definition to use a different range.
However, print is not a good name for such a macro; it's convention to use a longer name in all caps to avoid collisions with e.g. function names.
how can I repeat it N number of times based on some compile time argument where N is passed in that compiler argument
Just generate a C file, perhaps using another script (or metaprogram, that you could write in Guile, GPP, C++ or even C) to generate it. Configure your build automation tool (e.g. GNU make or ninja) accordingly.
Remember, you can #include a generated file.
For examples (of C file generators), see GNU bison or SWIG.
See also this blog (from the late Jacques Pitrat).
You could also be interested in libgccjit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With