Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat Code in C Based on Compile time Arguments

Tags:

c++

c

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?

like image 523
user7235699 Avatar asked Mar 28 '26 19:03

user7235699


2 Answers

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.

like image 137
Erlkoenig Avatar answered Mar 31 '26 13:03

Erlkoenig


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.

like image 35
Basile Starynkevitch Avatar answered Mar 31 '26 12:03

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!