2011-11-02 60 views
2
struct info _info; 

#define INIT(a, b, c, d)     \ 
    struct info _info = {a, b, c, d} 

這個工作用C的工作,但與G ++我得到:在頭初始化宏中的一個結構,必須在C和C++源

error: redefinition of ‘info _info’

INIT並不總是叫,有時_info會以其他方式初始化,這就是爲什麼這兩種方式都必須堅持。

語境:

我使用INIT中,這是獲得與G ++編譯的文件,但我還用它了GCC編譯的文件。所以問題是:我需要這個頭文件代碼在兩種語言中工作,而不管我是在c庫還是在C++庫中使用頭文件。

Kerrek指出,我可以用#ifdef來,所以我這樣做:

#ifndef __cplusplus 

struct info _info; 
#define INFO(a, b, c, d)     \ 
    struct info _info = {a, b, c, d} 

#else 

struct info _info; 
#define INFO(a, b, c, d)     \ 
      _info = {a, b, c, d} 
#endif 

但它仍然是行不通的,我在我使用宏行得到一個error: ‘_info’ does not name a type 我的cpp項目: INFO("Information", 2 ,"again", 4)

+2

請提供您使用'INIT'宏觀和它失敗的上下文。另外,你是否100%確定你沒有忘記宏定義中的反斜槓(這將與錯誤一致)?請複製並粘貼實際的錯誤代碼。 –

+0

@ AlexandreC.I補充說明我需要它在C++和c中工作 – Blub

+1

注意:以下劃線開頭的名稱在許多情況下都被保留,我邀請您切換到另一個命名約定。 –

回答

3

在C++中,變量聲明中不要說struct。下面應該工作:

struct info { int x, y, z, w; }; // type definition (elsewhere in your code) 

#define INIT(a, b, c, d) info _info = {a, b, c, d} 

INIT(1,2,3,4); 

因爲變量名是固定的,這個宏只能使用一次,任何給定的範圍,這是不明顯內部使用。爲了更靈活,我的變量名稱添加到宏:

#define DECLARE_AND_INIT(var, a, b, c, d) info var = {a, b, c, d} 
DECLARE_AND_INIT(my_info, 4, 5, 6, 7); 
+0

我需要它在C++和c中工作,我將包含在頭文件中的代碼包含到c和C++項目中。對不起,我不清楚。 – Blub

+0

錯......什麼?使用兩種不同的語言?我可以使用'__cplusplus'條件宏。 –

+1

@KerrekSB,使用'struct info'與在C++中使用普通的'info'一樣有效。 – avakar

0

如果我沒有記錯正確,您可以使用typedef,避免__cplusplus特定部分。

typedef struct taginfo { int x, y, z, w; } info; 
info _info; 
#define INFO(a,b,c,d) _info = {(a), (b), (c), (d)} 

...這應該在C和C++都有效。

Why should we typedef a struct so often in C?