命名空间中的内联函数提供对C++的未定义引用
Inline function in namespace gives undefined reference to, C++
我有一个非常简单的程序,在其中我定义了自己的命名空间,并且需要一个内联函数。这看起来像下面这样:
测试.h
#ifndef _TEST_H_
#define _TEST_H_
#include <iostream>
using namespace std;
namespace NS
{
class EXAMPLE
{
int i;
float f;
public:
void doSth();
};
}
#endif
测试.cpp
#include "test.h"
namespace NS
{
inline void EXAMPLE::doSth()
{
cout << i << f << "n";
}
}
主.cpp
#include "test.h"
int main()
{
NS::EXAMPLE e;
e.doSth();
return 0;
}
我这样编译它:g++ main.cpp test.cpp -o app
这导致
/tmp/ccFwG8do.o: In function `main':
main.cpp:(.text+0x10): undefined reference to `NS::EXAMPLE::doSth()'
collect2: error: ld returned 1 exit status
有什么想法吗?
inline
函数必须在使用它的所有翻译单元中定义为inline
,并具有相同的定义。
从本质上讲,这意味着 (1) 仅在一个翻译单元中使用它,或者 (2) 将定义放在使用该函数的每个翻译单元中包含的标头中。
用例(1)是人们想要inline
的暗示效果的地方,它指示编译器考虑是否在生成的机器代码中内联调用函数。用例(2)是关于inline
提供的保证,即在多个翻译单元中的这种使用不违反一个定义规则(或ODR,因为它通常被称为)。
相关文章:
- 编译C++时未定义的引用
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- c++11评估顺序(未定义的行为)
- 使用mysql c++连接器的未定义引用
- 从python调用openMP共享库时,未定义opnMP函数
- 在 Mac 上使用 CMAKE 将 FFTW 和 FFTWPP 链接到项目中时未定义的符号
- Cmake 链接问题:未定义对 Button::mousePressEvent(QGraphicsSceneMouseE
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 具有外部"c"和程序集的未定义函数
- 此增量后语句是否会导致未定义的行为?
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 在C++中使用内联方法时出现未定义的符号错误
- 对 Scalar ::Scalar() 的未定义引用