C 标题中的外部变量的未定义参考
undefined reference for the extern variable in C++ header
我在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.h
。A.h
中的extern
是A 声明,它设置了链接器的期望,即可以在另一个要链接的对象文件中找到一个全局变量,但是B.cpp
是变量是定义的。
只需确保在链接时间链接A.cpp
和B.cpp
。
相关文章:
- GTest EXPECT_EQ给出未定义的错误参考
- 在VSCode中编译C++给了我一个未定义的参考
- Armadillo正在为共享的lapack库获取未定义的参考
- 我对C++程序有一个未定义的参考,不知道如何处理它
- 使用Arduino IDE的构造函数的未定义参考错误
- 在C++中使用 CImg 的未定义参考错误
- gtest的未定义参考
- 未定义参考 cv::鱼眼::校准
- WEBRTC的未定义参考
- 如何编译ZBAR示例?(未定义参考..)
- 针对C 库链接时的未定义参考
- 命名空间外部变量的未定义参考/多重定义,C 结构问题
- 简单QT程序中的未定义参考
- 主要makefile中的未定义参考
- C 标题中的外部变量的未定义参考
- 对[class::function]的未定义引用/对[class]的typeinfo的未定义参考
- icu 54-未定义参考
- 信号上的QT未定义参考编译错误
- boost 1.58未定义参考
- QT未定义参考错误(Qextserialport)