所以像其他人說的那樣,不可以在宏中包含#include語句,因爲預處理器只會傳遞一次。但是,您可以使預處理器使用最近發現自己使用的粗糙技巧來做基本相同的事情。
認識到預處理器指令不會在宏內執行任何操作,但它們會在文件中執行某些操作。所以,你可以將你想要改變的代碼塊粘貼到一個文件中,把它看作是一個宏定義(可以用其他宏修改),然後在不同的地方包含這個僞宏文件(make確定它沒有包括警衛!)。它的行爲不像一個宏,但它可以實現一些非常類似宏的結果,因爲#include基本上只是將一個文件的內容轉儲到另一個文件中。
例如,考慮包含許多類似命名的標頭,這些標頭會分組。將它們全部寫出來,或者甚至它們是自動生成的都很乏味。
輔助宏頭:
/* tools.hpp */
#ifndef __TOOLS_HPP__
#def __TOOLS_HPP__
// Macro for adding quotes
#define STRINGIFY(X) STRINGIFY2(X)
#define STRINGIFY2(X) #X
// Macros for concatenating tokens
#define CAT(X,Y) CAT2(X,Y)
#define CAT2(X,Y) X##Y
#define CAT_2 CAT
#define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z))
#define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z))
// etc...
#endif
僞宏文件
/* pseudomacro.hpp */
#include "tools.hpp"
// NO INCLUDE GUARD ON PURPOSE
// Note especially FOO, which we can #define before #include-ing this file,
// in order to alter which files it will in turn #include.
// FOO fulfils the role of "parameter" in this pseudo-macro.
#define INCLUDE_FILE(HEAD,TAIL) STRINGIFY(CAT_3(HEAD,FOO,TAIL))
#include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp
#include INCLUDE_FILE(head2,tail2.hpp)
#include INCLUDE_FILE(head3,tail3.hpp)
#include INCLUDE_FILE(head4,tail4.hpp)
// etc..
#undef INCLUDE_FILE
源文件
/* mainfile.cpp */
// Here we automate the including of groups of similarly named files
#define FOO _groupA_
#include "pseudomacro.hpp"
// "expands" to:
// #include "head1_groupA_tail1.hpp"
// #include "head2_groupA_tail2.hpp"
// #include "head3_groupA_tail3.hpp"
// #include "head4_groupA_tail4.hpp"
#undef FOO
#define FOO _groupB_
#include "pseudomacro.hpp"
// "expands" to:
// #include "head1_groupB_tail1.hpp"
// #include "head2_groupB_tail2.hpp"
// #include "head3_groupB_tail3.hpp"
// #include "head4_groupB_tail4.hpp"
#undef FOO
#define FOO _groupC_
#include "pseudomacro.hpp"
#undef FOO
// etc.
這些包括可能您可以通過做這樣的事情部分自動將其列入甚至是在你想重複的代碼塊的中間(用FOO修改),就像一個由冰堅請求:macro definition containing #include directive
我還沒有廣泛使用這個技巧,但它使我的工作完成。顯然,它可以根據需要擴展爲具有儘可能多的「參數」,並且您可以在其中運行您喜歡的任何預處理器命令,並生成實際的代碼。你不能使用它創建的東西作爲另一個宏的輸入,就像你可以使用普通的宏一樣,因爲你不能將include包含在宏中。但它可以進入另一個僞宏:)。
其他人可能對其他限制有一些評論,並可能出錯:)。
你應該看看模板(如stbuton建議)。你當然應該避免需要這樣做。 – 2008-11-05 22:42:55
作爲一般規則,您應該將所有#include語句放在同一個地方(通常是頂部)。它使維護和調試代碼更簡單。 – helloandre 2008-11-06 01:30:20
我有一個基本上你想做的事情(使用預處理器)有點瘋狂的方式;請參閱我的回答:) http://stackoverflow.com/a/27830271/1447953 – 2015-01-07 23:17:27