根據我的理解,內聯函數可以在頭文件中以及在源文件中(使用inline關鍵字),默認情況下,頭文件中定義的memeber函數被編譯器內聯使用。共享庫的cpp文件中的內聯函數
我的問題是下面的源文件, add.h
#ifndef ADD_H
#define ADD_H
class Add {
public:
int add(int a, int b);
};
#endif /* ADD_H */
add.cpp
#include <iostream>
#include "add.h"
inline int Add::add(int a, int b) {
std::cout << "FUNC: " << __func__ << std::endl;
return a + b;
}
的main.cpp
#include "add.h"
int main() {
Add a;
a.add(6,7);
return 0;
}
如果我編譯add.cpp和main.cpp
g++ -c add.cpp
g++ -c main.cpp
g++ main.o add.o
它抱怨
main.o: In function `main':
main.cpp:(.text+0x1a): undefined reference to `Add::add(int, int)'
collect2: error: ld returned 1 exit status
看着add.o符號,
U __cxa_atexit
U __dso_handle
000000000000003d t _GLOBAL__sub_I_add.cpp
0000000000000000 t __static_initialization_and_destruction_0(int, int)
U std::ios_base::Init::Init()
U std::ios_base::Init::~Init()
0000000000000000 r std::piecewise_construct
0000000000000000 b std::__ioinit
它並沒有在它添加功能,我認爲是因爲該函數是內聯的.cpp。我的問題是,當我們共享庫時,是否需要在頭文件中定義內聯函數(示例中爲add.h),以便使用該庫的源文件(示例中的main.cpp)獲得內聯在obj創建本身上的函數? 在鏈接中使用-flto時沒有什麼區別,因爲函數不在add.o中?
不,不,不。如果函數內聯 - 它是內聯的。如果函數是在.h頭文件或.cpp源文件中定義的,則無關緊要;它是否是.dll/.so共享庫或.exe可執行文件無關緊要。有一點需要注意:我爲什麼會收到LNK2019解析的外部爲我的內聯函數?(https://blogs.msdn.microsoft.com/oldnewthing/20130509-00/?p=4413/) – paulsm4
你必須要在使用-flto編譯時間也一樣。你嘗試過嗎? – kchoose2