问题
which global variable can be used in the preprocessor directive file.cpp
int variable = 1;
#if variable >= 1
int a = 0;
#else
int a = 1;
#endif
or
file.cpp
const int variable = 1;
#if variable >= 1
int a = 0;
#else
int a = 1;
#endif
or file.cpp
#include "header.h"
// extern in variable; in the header.h
#if variable >= 1
int a = 0;
#else
int a = 1;
#endif
What are the rules which governs using the variables in the proprocessor directive? If a variable which can be consant folded, can it be used in the #if/#elif#else directives?
回答1:
Sorry, you can't do this at all. Variables are not visible to the preprocessor. The preprocessor is at its heart a text manipulator. The only values it can see are ones defined with #define
, not variables.
回答2:
Only macros defined with #define
will have their expected value in an #if
. All other symbols (more precisely, all identifiers that remain on an #if
line after macro expansion, except defined
and, in C++, certain "alternative spellings" of arithmetic operators, such as and
, or
, bitand
, bitor
, and compl
) are interpreted as having the value 0.
来源:https://stackoverflow.com/questions/14418258/using-variables-in-the-preprocessor-directives