I compiled the following program with both g++ (7.1) and clang++ (xcode 9.0) with -std=c++11 -Wall
and get the result:
g++
0x10052c050
0x10052c040
0x10052c040
clang++
0x108b74024
0x108b74018
0x108b74018
It means that the extern int a[];
and static int a[3];
declares same entity and have the same linkage (internal linkage).
//a.cpp
#include <stdio.h>
int a[3];
void f()
{
printf("%p\n", (void*)a);
};
//b.cpp
extern void f();
static int a[3];
void g()
{
printf("%p\n", (void*)a);
extern int a[];
printf("%p\n", (void*)a);
}
int main(int argc, char* argv[])
{
f();
g();
return 0;
}
but, in C++11 [3.9/6]:
... The declared type of an array object might be an array of unknown size and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points (“array of unknown bound of T” and “array of N T”) are different types. ...
int a[3];
and int a[];
are different types,
In C++11 [3.5/6]:
If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage.
"having the same name and type“ not compatible, so extern int a[];
shall not receives the linkage of the previous declaration(static int a[3];
),
and so, "Otherwise, if no matching entity is found, the block scope entity receives external linkage." is compatible.
My question is:
- Why the result of the compiler is not consistent with the C++11 standard wording?
- Or if my understanding is wrong, what's right?
Note: this question is different from error: extern declaration of 'i' follows declaration with no linkage