c++ - 错误 LNK2001 : unresolved external symbol "int const * const A_array" when I don't include the header in the definition file

标签 c++ extern

编译器:MS VS 2010

在我下面的程序中,我将 A_array 声明为 extern(告诉编译器它将在某处定义)并在 A.cpp 中定义它。

但是我遇到了链接器错误。即使 A.cpp 编译得很好,这意味着 A_array 应该已经分配了内存并且存在。是什么导致了这个问题?

注意:我已经在 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;
}
----------------------

输出:

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

更新 - 1:

当我在 A.cpp 中包含 A.h 时,代码编译、链接和工作正常。有人可以解释为什么 A.cpp 中需要包含这个内容吗?

最佳答案

问题是您在头文件中有一个(稍微不正确的)前向声明。

const int A_array[] = {10, 20, 30}; 的类型是数组或长度为 3。

const int A_array[]的类型是int指针或未定义长度的数组(它还不知道数组的长度)。

由于这些定义不完全匹配,编译器将不知道它们是相同的,除非您在 A.cpp 中包含 A.h,从那时起定义和声明将在同一个文件中,编译器将链接它们。

A.h extern const int A_array[3] 中进行声明应该可行。虽然在 A.cpp 中包含 A.h 会更正确。

关于c++ - 错误 LNK2001 : unresolved external symbol "int const * const A_array" when I don't include the header in the definition file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14872424/

相关文章:

c++ boost format float - 如何指定我不想要 .和以下零

c++ - 理解 C++ 中的 extern

c++ - 在类定义中使用 extern decl 说明符进行编程

我可以将 extern 用于宏吗?

c - 当全局变量和局部变量同名时访问全局变量

c - 如何声明 extern typedef struct?

c++ - float 数据类型错误解释

c++ - 将压缩文件嵌入到 C++ 程序中

c++ - 从 msvc v100 更新到 v140 平台工具集时出现 c2064 编译错误

使用 GCC 5.4 的 C++ 模板变量特化