命名空间中的内联函数提供对C++的未定义引用

Inline function in namespace gives undefined reference to, C++

本文关键字:C++ 未定义 引用 函数 命名空间      更新时间:2023-10-16

我有一个非常简单的程序,在其中我定义了自己的命名空间,并且需要一个内联函数。这看起来像下面这样:

测试.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,因为它通常被称为)。