Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the linkage of a name

Tags:

c++

c

An attempt to change the linkage of a name i is made in this code. Is it legal in C/C++?

static int i = 2;
int i;

int main()
{
   return 0;
}
like image 458
suraj kumar Avatar asked Dec 01 '10 15:12

suraj kumar


2 Answers

In C++ your code is ill-formed (you have multiple definitions of variable i) i.e a standard conformant compiler is required to issue an error message

$3.2.1 (C++03)

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

In C99 your code invokes Undefined Behaviour because 6.2.2/7 says

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

like image 128
Prasoon Saurav Avatar answered Oct 24 '22 01:10

Prasoon Saurav


No. In C I get this error:

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

In C++, these:

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

like image 21
sje397 Avatar answered Oct 24 '22 01:10

sje397