2016-06-29 33 views
0

我正在使用rapidjson,它是一個全部頭文件庫。在rapidjson.h,有一個宏觀RAPIDJSON_ASSERT,在我的cpp文件之一,我想重新定義它,所以我有我的文件的頂部驗證碼:是否可以將宏定義應用於單個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") 

這裏是whay是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,我會重新定義宏,但我希望能夠按編譯單元完成此操作。

+1

你在stdafx.h中包括rapidjson? – jaggedSpire

+0

模式看起來不對。您是否想要更改此翻譯單元的rapidjson中的宏,或者只是在翻譯單元內?如果是後者,請在rapidjson頭文件後重新定義。否則,rapidjson可能會簡單地重新定義宏本身 – KABoissonneault

+0

@jaggedSpire - 我沒有在stdafx.h中包含rapidjson.h,所以我不確定爲什麼它不會覆蓋宏。 – bpeikes

回答

1

好像你想改變RAPIDJSON_ASSERT定義爲rapidjson代碼本身

如果是這樣,你需要定義它的地方後添加的#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

+0

我在問題中添加了一些信息,但文檔指定您應該在包含文件之前定義RAPIDJSON_ASSERT,而不是之後。沒有道理的是,似乎#ifndef語句rapidjson.h在某些編譯單元中只能被檢查一次。 – bpeikes

+1

完全關閉預編譯頭並嘗試? –

+0

我在想預編譯頭文件可能是問題。我會試一試。 – bpeikes

相關問題