【发布时间】:2016-01-15 19:12:55
【问题描述】:
我想通过使用宏的旧值重新定义宏来改变某些代码的工作方式。但是,由于似乎评估宏的方式,它对我不起作用。我想要的是立即评估#define 中的宏,这样类似
#define A B
将A 定义为B 在#define 时的值,并且不受以后重新定义B 的影响。
这个例子有效:
// in a header somewhere, can't change this
#define A 1
// wrapper code to replace the number with a run-time expression
#define OLD_A 1
#define NEW_A 42
#undef A
bool flag = false;
#define A ( flag ? NEW_A : OLD_A)
// user code, don't want to change this
//
#include <stdio.h>
main()
{
flag = false;
printf("A is %d\n",A);
flag = true;
printf("A is %d\n",A);
}
输出(按预期):
1$ ./cpptest
A is 1
A is 42
但是,如果我将OLD_A 的定义更改为A,则它不会编译。
// in a header somewhere, can't change this
#define A 1
// wrapper code to replace the number with a run-time expression
#define OLD_A A /// <------ here
#define NEW_A 42
#undef A
bool flag = false;
#define A ( flag ? NEW_A : OLD_A)
// user code, don't want to change this
//
#include <stdio.h>
main()
{
flag = false;
printf("A is %d\n",A);
flag = true;
printf("A is %d\n",A);
}
构建失败:
$ make cpptest
icpc cpptest.cpp -o cpptest
cpptest.cpp(19): error: identifier "A" is undefined
printf("A is %s\n",A);
^
我知道这是一种将代码设计为可维护的可怕方式,但这是一次性旧版本的补丁,在这种情况下,它对我来说很有意义,因为它需要对其他工作代码进行较少的更改。
【问题讨论】:
标签: c-preprocessor