2010-12-01 160 views
7

在此代碼中嘗試更改名稱i的鏈接。在C/C++中它合法嗎?更改名稱的鏈接

static int i = 2; 
int i; 

int main() 
{ 
    return 0; 
} 
+2

你不試試呢? – sje397 2010-12-01 15:17:46

+6

什麼是C/C++? 。 – 2010-12-01 15:23:27

+3

@Charles C和C++。 – 2010-12-01 15:25:36

回答

10

在C++是形成不良的代碼(你有多個定義變量i)即需要標準一致性編譯器來發出錯誤消息

$ 3.2.1(C++ 03)

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type or template.

在C99您的代碼調用未定義行爲,因爲6.2.2/7說

If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

1

號在CI得到這個錯誤:

test.c:2: error: non-static declaration of ‘i’ follows static declaration
test.c:1: note: previous definition of ‘i’ was here

在C++中,這些:

test.cpp:2: error: redefinition of ‘int i’
test.cpp:1: error: ‘int i’ previously defined here