For a loop macro that is deployed at the pre-processor stage?

I want to use gcc pre-processor to write almost the same code declaration for 500 times. for example, for demonstration purposes, I would like to use the FOR_MACRO macro:

 #define FOR_MACRO(x) \ #for i in {1 ... x}: \ const int arr_len_##x[i] = {i}; 

and calling FOR_MACRO(100) will be converted to:

 const int arr_len_1[1] = {1}; const int arr_len_2[2] = {2}; ... const int arr_len_100[100] = {100}; 
+7
c gcc c-preprocessor linux-kernel
source share
4 answers

This is not a good idea:

Perhaps, in principle, using a preprocessor means that you must manually unroll the loop at least once, as a result, you will get some arbitrary limit determined by the implementation at the depth of the loop, and all the operators will be generated on one line.

It is better to use the scripting language of your choice to generate the code (possibly in a separate includeable file) and integrate it with the build process.

+10
source share

You can use Order-PP for this if you desperately need.

This is a scripting language implemented in the preprocessor. This means that it is conceptually similar to using a scripting language to generate C code (in fact, the same), except that there are no external tools, and the script is executed simultaneously with the C compiler: everything is executed using C macros. Despite the fact that it is built on a preprocessor, there are no real restrictions for cyclic iterations, recursion depths or anything like that (the limit is somewhere in the billions, you do not need to worry about that).

To fix the code requested in the sample question, you can write:

 #include <order/interpreter.h> ORDER_PP( // runs Order code 8for_each_in_range(8fn(8I, 8print( 8cat(8(const int arr_len_), 8I) ([) 8I (] = {) 8I (};) )), 1, 101) ) 

I can’t understand why you will do this, instead of just integrating an external language such as Python into your build process (the order can be implemented using macros, but it still needs a separate language), but there is an option.

The order only works with GCC, as far as I know; other preprocessors exit the stack too quickly (even Clang) or do not conform to the standard.

+3
source share

Instead of providing you with a solution specifically for your problem, are you sure that it cannot be handled better?

Perhaps it would be better

  • use one array with another size
  • populate data with an array at runtime, since you obviously want to populate the first record of each array. If you leave the array uninitialized, it (if defined at the module level) will be placed in the .bss segment instead of .data and it will probably require less space in the binary.
+1
source share

You can use, for example, P99 to deploy this preprocessor process. But due to the limited capabilities of the preprocessor, this has a limit, and this limit is usually below 500 .

+1
source share

All Articles