我需要定义内联函数来提高代码的性能。目前函数声明在 .h 文件中,定义在 .cpp 文件中。我在每个函数声明的前面添加了 inline 关键字,但出现链接错误。是否可以将内联函数的声明和定义分开?
最佳答案
您可以很好地将声明和定义分开,但是该定义必须在使用该函数的每个翻译单元中可用,例如:
#include <iostream>
inline void foo();
int main() {
foo();
}
inline void foo() {
std::cout << "Hi\n";
}
完全合法且正确。
n3290 § 7.1.2.4 的确切引述是:
An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [ Note: A call to the inline function may be encountered before its definition appears in the translation unit. —end note ]
§ 3.2 基本上说它必须在任何地方都相同,甚至是重载决议等。
关于c++ - 是否可以将内联函数的声明和定义分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11428147/