C 标题中的外部变量的未定义参考

undefined reference for the extern variable in C++ header

本文关键字:未定义 参考 变量 外部 标题      更新时间:2023-10-16

我在C 中有一些代码:

// A.h
extern const char *names[3];
// B.cpp
#include "A.h"
const char *names[3] = {
   "Name1",
   "Name2"
   "Name3"
};
void getName()
{
    char *name;
    strncpy(name, names[0], 5);
};
// C.cpp
#include "A.h"

然后,当我构建它时,它会生成以下错误:

对"名称"的未定义引用什么原因和如何修复?

您在示例中有一些错误,我认为您不仅复制/粘贴源。就像 const char *names[3]; = {行中的分号一样,或" name2"旁边的字符串列表中的缺失逗号

所以您的问题。您不应在您的b.cpp中包含a.h,我的意思是应删除线#include "A.h"。您包括标题文件,并仅在其他CPP文件中使用*names指针的地方使用Extern关键字。

B.cpp不应包括 A.hA.h中的extern是A 声明,它设置了链接器的期望,即可以在另一个要链接的对象文件中找到一个全局变量,但是B.cpp是变量是定义的

只需确保在链接时间链接A.cppB.cpp