我正在使用 rapidjson,它是一个全头文件库。在 rapidjson.h
中,有一个宏 RAPIDJSON_ASSERT
,在我的一个 cpp 文件中,我想重新定义它,所以我的文件顶部有这段代码:
#include "stdafx.h" // for windows
#pragma push_macro("RAPIDJSON_ASSERT")
#define RAPIDJSON_ASSERT(x) if(!(x)) throw std::logic_error("rapidjson exception");
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
....
....
#pragma pop_macro("RAPIDJSON_ASSERT")
这是 rapidjson.h
定义 RAPIDJSON_ASSERT
的原因:
#ifndef RAPIDJSON_ASSERT
#include <cassert>
#define RAPIDJSON_ASSERT(x) assert(x)
#endif // RAPIDJSON_ASSERT
文档指出要覆盖 RAPIDJSON_ASSERT
逻辑,您只需在包含任何文件之前定义 RAPIDJSON_ASSERT
。
问题是当我在调试器中运行代码时,RAPIDJSON_ASSERT
没有被重新定义。我检查了 stdafx.h
是否有任何包含 rapidjson 头文件的内容,但没有任何内容。
我假设每个编译单元都应该通过头文件运行。
请注意,如果我将宏的重新定义移动到 stdafx.h
中,我会重新定义宏,但我希望能够按编译单元进行。
最佳答案
看来您想为 rapidjson 代码本身更改 RAPIDJSON_ASSERT 的定义
如果是这样,需要在定义的地方后面加上#define。除非你想编辑 rapidjson.h 文件,否则唯一的选择就是这样做:
#include "stdafx.h" // for windows
// One would assume that the macro gets defined somewhere inside here
#include "rapidjson/rapidjson.h"
// Compiler will complain about macro redefinition without this #undef
#undef RAPIDJSON_ASSERT
#define RAPIDJSON_ASSERT(x) if(!(x)) throw std::logic_error("rapidjson exception");
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
现在,对于其余的头文件,RAPIDJSON_ASSERT 的定义已更改。您不需要 push_macro 和 pop_macro 恶作剧 - 宏仅对每个单元有效
请注意,使用#define 为库重新定义东西并不是一件好事
关于c++ - 可以将宏重新定义应用于单个 cpp 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38108876/