“内联函数应该放在头文件中,因为内联函数的定义对于编译器而言必须是可见的,以便编译器能够在调用点内联展开该函数的代码,所以仅有的函数原型不够。并且,与一般函数不同,内联函数有可能在程序中的定义不止一次,此时必须保证在所有源文件中定义完全相同,把内联函数的定义放在头文件可以确保这一点。”
可以看看下面这个例子。
fact.cpp
#include <iostream> #include <cstdlib> #include "Chapter6.h" using namespace std; inline void func(int a) { static int s = 0; int m = 0; a++, s++, m++; cout << "A:" << a << endl; cout << "S:" << s << endl; cout << "M:" << m << endl; cout << endl; }
FactMin.cpp
#include <iostream> #include <cstdlib> #include "Chapter6.h" using namespace std; int main() { for (size_t i = 0; i < 10; i++) { func(0); } system("PAUSE"); return 0; }
Chapter6.h
#pragma once #ifndef Chapter6_H #define Chapter6_H void func(int a); #endif // Chapter6_H
编译时报出:
LNK2019 Project438 C:\Users\10245\source\repos\Project438\Project438\FactMin.obj
LNK1120 1 Project438 C:\Users\10245\source\repos\Project438\Debug\Project438.exe 1
根据上面说的,我们将fact.cpp的函数定义放进Chapter6.h就可以编译成功了。
Chapter6.h
#pragma once #ifndef Chapter6_H #define Chapter6_H #include <iostream> using namespace std; inline void func(int a) { static int s = 0; int m = 0; a++, s++, m++; cout << "A:" << a << endl; cout << "S:" << s << endl; cout << "M:" << m << endl; cout << endl; } #endif // Chapter6_H
FactMin.cpp保留不变,fact.cpp删去
VS2017 运行结果: