2010-08-15 142 views
1

下(測試用gcc -E blah.c)時,意外的預定義宏的行爲:粘貼標記

#define UNUSED(type) type UNUSED_ ## __COUNTER__ 
UNUSED(char const *) 
UNUSED(int) 

生成:

char const * UNUSED__COUNTER__ 
int UNUSED__COUNTER__ 

我期待:

char const * UNUSED0 
int UNUSED1 

我試着調用另一個宏,將參數括在括號內無濟於事。 如果我不粘貼令牌,它似乎工作正常。 documentation特別提到在令牌粘貼中使用__COUNTER__

我在做什麼錯?

回答

1

用gcc 4.4做實驗,這個工程:

#define UNUSED(type) UNUSED_(type, __COUNTER__) 
#define UNUSED_(type, counter) UNUSED__(type, counter) 
#define UNUSED__(type, counter) type UNUSED_ ## counter 
UNUSED(char const *) 
UNUSED(int) 

但如果我拿出中間體即使只有一個級別不工作。

-1

我相信你一定「雙擴張」吧:

#define STR(x) #x 
#define UNUSED(type) type UNUSED_ ## STR(__COUNTER__) 
UNUSED(char const *) 
UNUSED(int) 
+0

沒有這個運氣:'char const * UNUSED_STR(0)'和'int UNUSED_STR(1)' – 2010-08-15 15:40:11

+0

UNUSED_問題之後的空間是什麼? – Chubsdad 2010-08-15 15:42:09

+0

你當然不是有意串通,是嗎?如果這一切工作,它會產生的東西,如'char const * UNUSED「0」'... – zwol 2010-08-15 16:48:42

1

__COUNTER__GCC 4.3只推出 - 如果你碰巧使用早期版本,宏根本就沒有定義。在這種情況下,宏可能值得研究。

在較新的GCC版本中,您仍然需要一種不同的串接方法,因爲##可防止其參數擴展。因此,你必須先使用##之前將其展開:

#define CAT(a, b) CAT_I(a, b) 
#define CAT_I(a, b) CAT_II(a ## b) 
#define CAT_II(x) x 
#define UNUSED(type) type CAT(UNUSED_, __COUNTER__) 

如果你已經在使用升壓,BOOST_PP_CAT()爲您提供了相同的功能。

+0

對不起,C++標記是不正確的,所以SO將cpp更改爲C++ ...顯然有人沒有聽說過C預處理器 – 2010-08-15 16:43:36

+0

@Matt:C和C++的答案是一樣的,即使Boost.PP也適用於這兩者。 – 2010-08-15 16:45:23

+0

我的意思是C++ isms(如Boost)在這裏沒有用處。但是,謝謝你的信息。 – 2010-08-15 16:46:06