2

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?

user7235699
  • 431
  • 2
  • 13

2 Answers2

6

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.

Erlkoenig
  • 2,664
  • 1
  • 9
  • 18
2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547