函数内联问题Function Inlining Problems

如果你使用的是函数内联,则必须:If you are using function inlining, you must:

  • 在包含的头文件中实现内联函数。Have the inline functions implemented in the header file you include.

  • 在头文件中打开了内联。Have inlining turned ON in the header file.

// LNK2019_function_inline.cpp
// compile with: /c
// post-build command: lib LNK2019_function_inline.obj
#include <stdio.h>
struct _load_config_used {
   void Test();
   void Test2() { printf("in Test2\n"); }
};

void _load_config_used::Test() { printf("in Test\n"); }

然后,And then,

// LNK2019_function_inline_2.cpp
// compile with: LNK2019_function_inline.lib
struct _load_config_used {
   void Test();
   void Test2();
};

int main() {
   _load_config_used x;
   x.Test();
   x.Test2();   // LNK2019
}

如果使用的是 #pragma inline_depth 编译器指令,请确保设置的值为2或更大。If you are using the #pragma inline_depth compiler directive, make sure you have a value of 2 or greater set. 如果值为零,则将关闭内联。A value of zero will turn off inlining. 此外,请确保使用的是 /Ob1/Ob2 编译器选项。Also make sure you are using the /Ob1 or /Ob2 compiler options.

在不同模块上混合内联和非内联编译选项有时会导致问题。Mixing inline and non-inline compile options on different modules can sometimes cause problems. 如果在创建 c + + 库时打开了函数内联 (/Ob1/Ob2) 但描述函数的相应标头文件已关闭 (不) 选项,您将收到错误 LNK2001。If a C++ library is created with function inlining turned on (/Ob1 or /Ob2) but the corresponding header file describing the functions has inlining turned off (no option), you will get error LNK2001. 函数不会从头文件中内联到代码中,但由于它们不在库文件中,因此没有用于解析引用的地址。The functions do not get inlined into the code from the header file, but since they are not in the library file there is no address to resolve the reference.

同样,使用函数内联的项目还在 .cpp 文件而不是头文件中定义函数也会获得 LNK2019。Similarly, a project that uses function inlining yet defines the functions in a .cpp file rather than in the header file will also get LNK2019. 标头文件被视为适当的位置,但仅当 .cpp 文件通过编译器时才会内联函数;因此,在其他模块中使用时,链接器将函数视为未解析的外部函数。The header file is included everywhere deemed appropriate, but the functions are only inlined when the .cpp file passes through the compiler; therefore, the linker sees the functions as unresolved externals when used in other modules.

// LNK2019_FIP.h
struct testclass {
   void PublicStatMemFunc1(void);
};

然后and then,

// LNK2019_FIP.cpp
// compile with: /c
#include "LNK2019_FIP.h"
inline void testclass::PublicStatMemFunc1(void) {}

然后and then,

// LNK2019_FIP_2.cpp
// compile with: LNK2019_FIP.cpp
// LNK2019 expected
#include "LNK2019_FIP.h"
int main() {
   testclass testclsObject;

   // module cannot see the implementation of PublicStatMemFunc1
   testclsObject.PublicStatMemFunc1();
}

请参阅See also

链接器工具错误 LNK2019Linker Tools Error LNK2019