I have searched a lot for the extern-array-pointer problem but still feeling confused.
In the following code:
// example 1
//1.cpp
int a[]={1,2,3}; //the array a
//main.cpp
extern int*a; //the pointer a
In main.cpp, when I use printf to print a, it gives me 1 which is the first four bytes of the array a defined in 1.cpp. And printing &a gives me 0x1234(for example) which is the address of the first element of the array a defined in 1.cpp.
It acts like the pointer a was connected with the array a by the address 0x1234 forcibly. Thus, the value of the pointer a is what located at 0x1234, which is 1, since sizeof(int*) == sizeof(int) in 32-bit.
I have learned that the linker needs the unresolved symbol table and the export symbol table to link declaration to definition.
While compiling 1.cpp, symbol a was added to the export symbole table and while compiling main.cpp, symbol a was added to the unresolved symbol table. They should be named differently since their type is not the same.
In fact the linker could check the types of variable, because:
//example 2
//1.cpp
int a[]={1,2,3}
//2.cpp
extern char *a;
throwing a linking error that char *a was unresolved, but they don't mixed forcibly, linker could catch the error.
In single unit:
//example 3
int a[] = {1,2,3};
int *ptr = a;
the compiler convert the a variable to a temporary int * implicitly, but can not do that while in different units.
So why extern a pointer to receive an array is not caught by the linker. What does the linker actually do?
Thank you so much!