C预处理程序:及早评估宏 [英] C Preprocessor: Evaluate macro early
问题描述
请考虑以下设置:
a.h
#define A 5
#define B A
#undef A
#define A 3
交流
#include "a.h"
#include <stdio.h>
int main()
{
printf("%d\n", B);
return 0;
}
虽然这非常合理地打印了3,但有没有办法使它打印5,即是否已经在a.h的第二行将5替换为A?
While this very reasonably prints 3, is there a way to make it print 5, i.e. do the substitution of 5 for A already at line two of a.h?
推荐答案
不,没有办法.除非您知道A
的所有可能值,并且它们始终是整数,否则您可以依次费力地测试每个值:
No, there's no way to do that. Unless you know all the possible values of A
, and they are always integers, in which case you can laboriously test each one in turn:
#if A == 0
# define B 0
#elif A == 1
# define B 1
#elif A == 2
# define B 2
/* ... and a very long etc. */
#endif
如果用例仅涉及整数,则有更多选择.例如,您可以声明B
为static const int
或enum
(取决于语言),而不是宏,这显然会使用宏的当前值.如果您真的想要宏,则Boost预处理库具有 的上述#if
费力的序列的实现(巧妙地减少了log(N)而不是N所需的预处理程序语句的数量).
If your use case only involves integers, you have more options. You could, for example, declare B
to be static const int
or enum
(depending on language) instead of a macro, which would obviously use the current value of the macro. If you really really want macros, the Boost preprocessing library has an implementation of the laborious sequence of #if
s above (with some cleverness to reduce the number of preprocessor statements needed to log(N) instead of N).
#define
预处理程序指令中没有宏替换;该事实已在§ 6.10段中涵盖. C标准的第7条(C ++标准的第16条第6款,用相同的措词):
There is no macro substitution in the #define
preprocessor directive; this fact is covered by §6.10 para. 7 of the C standard (§16 para. 6 of the C++ standard, with identical wording):
除非另有说明,否则预处理指令中的预处理令牌不会进行宏扩展.
The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated.
在#if
和#include
指令的描述中,该标准指定确实发生了宏替换,这就是上述#if
解决方案有效的原因(以及Boost实现,该实现也使用了计算出的#include
).
In the description of the #if
and #include
directives, the standard specifies that macro replacement does occur, which is why the #if
solution above works (and the Boost implementation, which also uses a computed #include
).
这篇关于C预处理程序:及早评估宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!