[英]error LNK2001: unresolved external symbol “int const * const A_array” when I don't include the header in the definition file
Compiler : MS VS 2010 编译: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. 在我下面的程序中,我将A_array声明为extern(告诉它将在某处定义编译器)并在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.
即使A.cpp编译正常,这意味着A_array应该已经分配了内存并且存在。 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. 注意:我搜索了SO的链接器错误代码,但我仍然找不到此错误的确切原因。
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: 更新 - 1:
When I include Ah in A.cpp the code compiles, links and works fine. 当我在A.cpp中包含Ah时,代码编译,链接和工作正常。 Can someone explain why this is inclusion is need in A.cpp?
有人可以解释为什么在A.cpp中需要包含这个内容吗?
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};
const int A_array[] = {10, 20, 30};
的类型const int A_array[] = {10, 20, 30};
is an array or length 3. 是数组或长度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). const int A_array[]
的类型是int
指针或未定义长度的数组(它还不知道数组的长度)。
Since these definitions don't match up exactly, the compiler will not know they are the same, unless you include Ah
in A.cpp
, since then both the definition and declaration will be in the same file and the compiler will link them. 由于这些定义不完全匹配,编译器不会知道它们是相同的,除非你在
A.cpp
包含Ah
,因为那时定义和声明都将在同一个文件中,编译器将链接它们。
Making the declaration in Ah
extern const int A_array[3]
should work. 在
Ah
extern const int A_array[3]
应该有效。 Though including Ah
in A.cpp
would be more correct. 虽然在
A.cpp
包括Ah
会更正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.