这最初是作为c++ macros with memory?
的答案发布的但不知怎的,我无法得到这个编译。我可能会在这里遗漏一些东西。 (我觉得这是C ++可以做的事情)
的main.cpp
#include <iostream>
using namespace std;
const char * hello = "hello";
const char * world = "world";
#define VAR
#define MEMORIZE world
#include "memorize.h"
#define MEMORIZE hello
#include "memorize.h"
int main() {
cout << VAR << endl;
return 0;
}
memorize.h
#undef VAR
#ifndef MEMORIZE
# error "No Argument to memorize.h"
#endif
#define VAR MEMORIZE
#undef MEMORIZE
我得到的编译错误是:
[100%] Building CXX object CMakeFiles/main.dir/main.cpp.o
error: use of undeclared identifier 'MEMORIZE'
cout << VAR << endl;
^
note: instantiated from:
#define VAR MEMORIZE
^
1 error generated.
make[2]: *** [CMakeFiles/main.dir/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/main.dir/all] Error 2
make: *** [all] Error 2
我真的想让这个记忆在预处理阶段起作用。有人可以帮忙吗?我认为BOOST_PP_COUNTER
中的1.49
也使用了这种技术,但我无法弄清楚如何。
答案 0 :(得分:1)
您只使用一个VAR
值(最后一个),因为它只能使用一个值。如果你想根据上下文用VAR
来表示不同的东西,你需要在每个include之后都有源语句。
#define xstr(a) str(a)
#define str(a) #a
int main() {
#define MEMORIZE world
#include "memorize.h"
cout << VAR << endl;
#undef MEMORIZE
#define MEMORIZE hello
#include "memorize.h"
cout << VAR << endl;
return 0;
}
memorize.h:
#undef VAR
#ifndef MEMORIZE
# error "No Argument to memorize.h"
#endif
#define VAR xstr(MEMORIZE)
答案 1 :(得分:0)
您正在将VAR
宏设置为令牌MEMORIZE
,您将立即取消定义。这一行:
cout << VAR << endl;
结束为:
cout << MEMORIZE << endl;
并且由于MEMORIZE
未声明,因此您会收到错误消息。它认为MEMORIZE
是一个变量名。
答案 2 :(得分:0)
您需要移动#undef MEMORIZE
行 - 将其从memorize.h中删除,然后在#define MEMORIZE
出现的任何地方放置。