内联函数的未解析符号

Unresolved symbol for inline function

本文关键字:符号 函数      更新时间:2023-10-16

请考虑以下代码:

测试2.h:

#ifndef ABCD
#define ABCD
#ifdef __cplusplus
extern "C" {
#endif
void Foo();
#ifdef __cplusplus
}
#endif
#endif // ABCD

测试2.cpp

#include "StdAfx.h"
#include "Test2.h"
inline void Foo()
{
}

测试.cpp:

#include "stdafx.h"
#include "Test2.h"
int _tmain(int argc, _TCHAR* argv[])
{
Foo();
return 0;
}

当我编译此代码时,出现LNK2019错误(未解析的外部符号_Foo)。 我可以通过两种方式解决它。

  1. 删除内联关键字。
  2. 将 extern 添加到函数声明中。

假设我想要内联这个函数,为什么我必须在声明中添加 extern?

我使用VS2008。

谢谢。

C++11 标准第 3.2.3 段:

内联函数应在使用它的每个翻译单元中定义

您有 2 个翻译单元,首先由Test2.cpp...:

// ... code expanded from including "StdAfx.h"
extern "C" { void Foo(); }
inline void Foo() { }

。第二个由Test.cpp制成:

// ... code expanded from including "StdAfx.h"
extern "C" { void Foo(); }
int _tmain(int argc, _TCHAR* argv[])
{
Foo();
return 0;
}

在第二个 TU 中,缺少Foo的定义。

为什么不简单地将Foo的定义放入头文件中?如果编译器看不到其代码,则无法内联其代码。