gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:02:46 25 4
gpt4 key购买 nike

编译器: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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com