2010-12-01 198 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