【发布时间】:2015-12-10 17:28:47
【问题描述】:
据我了解,内联函数可以放在头文件中,也可以放在源文件中(使用 inline 关键字),默认情况下,头文件中定义的成员函数会被编译器尝试内联。
我的问题是以下源文件, 添加.h
#ifndef ADD_H
#define ADD_H
class Add {
public:
int add(int a, int b);
};
#endif /* ADD_H */
添加.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 可执行文件并不重要。一个警告:Why am I getting LNK2019 unresolved external for my inline function?
-
您也必须在编译时使用 -flto。你试过了吗?
标签: c++ optimization shared-libraries inline compiler-optimization