内联函数的未解析符号
Unresolved symbol for inline function
请考虑以下代码:
Test2.h:
#ifndef ABCD
#define ABCD
#ifdef __cplusplus
extern "C" {
#endif
void Foo();
#ifdef __cplusplus
}
#endif
#endif // ABCD
Test2.cpp
#include "StdAfx.h"
#include "Test2.h"
inline void Foo()
{
}
Test.cpp:
#include "stdafx.h"
#include "Test2.h"
int _tmain(int argc, _TCHAR* argv[])
{
Foo();
return 0;
}
当我编译此代码时出现 LNK2019 错误(未解析的外部符号 _Foo)。
我可以通过两种方式解决。
- 删除内联关键字。
- 在函数声明中添加 extern。
假设我想要内联这个函数,为什么我必须在声明中添加 extern?
我用的是VS2008
谢谢。
C++11 标准第 3.2.3 段:
An inline function shall be defined in every translation unit in which it is odr-used.
您有 2 个翻译单元,第一个来自 Test2.cpp
...:[=17=]
// ... 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
的定义放到头文件里呢?如果编译器看不到它,它就无法内联它的代码。
请考虑以下代码:
Test2.h:
#ifndef ABCD
#define ABCD
#ifdef __cplusplus
extern "C" {
#endif
void Foo();
#ifdef __cplusplus
}
#endif
#endif // ABCD
Test2.cpp
#include "StdAfx.h"
#include "Test2.h"
inline void Foo()
{
}
Test.cpp:
#include "stdafx.h"
#include "Test2.h"
int _tmain(int argc, _TCHAR* argv[])
{
Foo();
return 0;
}
当我编译此代码时出现 LNK2019 错误(未解析的外部符号 _Foo)。 我可以通过两种方式解决。
- 删除内联关键字。
- 在函数声明中添加 extern。
假设我想要内联这个函数,为什么我必须在声明中添加 extern?
我用的是VS2008
谢谢。
C++11 标准第 3.2.3 段:
An inline function shall be defined in every translation unit in which it is odr-used.
您有 2 个翻译单元,第一个来自 Test2.cpp
...:[=17=]
// ... 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
的定义放到头文件里呢?如果编译器看不到它,它就无法内联它的代码。