Reputation: 1158
Compiler : MS VS 2010
In my program below, I am declaring A_array as extern (telling it the compiler it will be defined somewhere) and defining it in A.cpp.
However I am getting a linker error. Even though A.cpp compiled fine which means A_array should have been allocated memory and be present. What could be causing this issue?
Note: I have searched SO for the linker error code and I still could not find the precise reason for this error.
A.h
----------------------
#ifndef INC_A_H
#define INC_A_H
extern const int A_array[];
#endif
----------------------
A.cpp
----------------------
const int A_array[] = {10, 20, 30};
----------------------
B.cpp
----------------------
#include <iostream>
#include "A.h"
int main()
{
for(int i=0; i<3; i++)
{
std::cout << A_array[i] <<"\n";
}
int x;
std::cin >> x;
return 0;
}
----------------------
Output:
1>ClCompile:
1> B.cpp
1> A.cpp
1> Generating Code...
1>B.obj : error LNK2001: unresolved external symbol "int const * const A_array" (?A_array@@3QBHB)
1>Visual Studio 2010\Projects\test_extern\Debug\test_extern.exe : fatal error LNK1120: 1 unresolved externals
Update - 1:
When I include A.h in A.cpp the code compiles, links and works fine. Can someone explain why this is inclusion is need in A.cpp?
Upvotes: 3
Views: 2362
Reputation: 55609
The problem is that you have a (slightly incorrect) forward declaration in the header file.
The type of const int A_array[] = {10, 20, 30};
is an array or length 3.
The type of const int A_array[]
is int
pointer or array of undefined length (it can't know the length of the array yet).
Since these definitions don't match up exactly, the compiler will not know they are the same, unless you include A.h
in A.cpp
, since then both the definition and declaration will be in the same file and the compiler will link them.
Making the declaration in A.h
extern const int A_array[3]
should work. Though including A.h
in A.cpp
would be more correct.
Upvotes: 4