Error LNK2001: Unresolved external symbol "int const * const A_array" when I do not include header in definition file
Compiler: MS VS 2010
In my program below, I declare A_array as extern (telling it that the compiler will be defined somewhere) and defining it in A.cpp.
However, I am getting a linker error. Even though A.cpp compiled perfectly, which means A_array must be memory allocated and present. What could be causing this problem?
Note. I searched SO for the linker error code and I still couldn't find the exact cause of 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 Ah in A.cpp it compiles the code, links and works fine. Can someone explain why this inclusion is necessary in A.cpp?
source to share
The problem is that there is a (slightly incorrect) declaration in the header file.
Type const int A_array[] = {10, 20, 30};
is array or length 3.
The type const int A_array[]
is a pointer int
or array of undefined length (it doesn't know the length of the array yet).
Since these definitions don't match exactly, the compiler won't know they are the same unless you include A.h
in A.cpp
, since then the definition and declaration will be in the same file and the compiler will link them.
Fulfilling the declaration in A.h
extern const int A_array[3]
should work. Although inclusion A.h
in A.cpp
would be more correct.
source to share