Just curious. Imagine I need to have a #define A
that is the sum of n numbers, and those n numbers have a meaning I'd like to make explicit, but only for the computation of A
, to improve readiblity,
instead of writing n macros or just writing #define A <result_of_the_sum>
.
Is there a way I could limit the reach of these n #define
directives to just the definition of A ? Just as in C one would do :
int a = 0;
{
int b = 1;
int c = 2;
int d = 3;
a = b c d;
} // end of b,c,d scope.
My intention is to have A
defined when compiling but no definition for the other n
defines used to compute A
, since these would only be useful to understand the code better.
Edit:
Imagine I have these macros:
#define MEANINGFUL_NUMBER_1 1
#define MEANINGFUL_NUMBER_2 2
#define MEANINGFUL_NUMBER_3 3
And I have a macro, A
that is the sum of them, and I like someone reading my code to understand the value of A not just see it defined straightforwardly, i.e. #define A (MEANINGFUL_NUMBER_1 ... MEANINGFUL_NUMBER_N)
, such that only A is substituted before compilation but MEANINGUL_NUMBER_*
is not.
CodePudding user response:
Is there a way to manipulate preprocessor define scope in C
No.
Is there a way I could limit the reach of these n #define directives to just the definition of A ?
No.
Note that macros are evaulated upon use. That means that everything has to be visible when the macro is used. You can #undef
all the macros after all usages, ergo "limit the reach" in that way.
In C, there are no namespaces. In C use prefixes. You would do:
#define LIB_PRIV_B 1
#define LIB_PRIV_C 2
#define LIB_PRIV_D 3
#define LIB_A (LIB_PRIV_B LIB_PRIV_C LIB_PRIV_D)
If you really do not want the numbers to leak into C, then use something to generate the C source code, which also gives you more power to the preprocessor side. Use jinja2, m4, php or python, and configure your build system to properly handle the generation dependency.