[英]Inline function in namespace gives undefined reference to, C++
我有一個非常簡單的程序,我在其中定義自己的命名空間,需要一個內聯函數。 這看起來像下面這樣:
test.h
#ifndef _TEST_H_
#define _TEST_H_
#include <iostream>
using namespace std;
namespace NS
{
class EXAMPLE
{
int i;
float f;
public:
void doSth();
};
}
#endif
TEST.CPP
#include "test.h"
namespace NS
{
inline void EXAMPLE::doSth()
{
cout << i << f << "\n";
}
}
main.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,因為它經常被稱為)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.