【问题标题】:Linker unresolved external symbol for inline function链接器无法解析内联函数的外部符号
【发布时间】:2016-09-21 21:00:59
【问题描述】:

我正在使用 Visual Studio 2015 开发 C++ 解决方案。

我有一个带有这个声明的 cpp 源文件和头文件 hpp。

标题:

#ifndef MyLib__FREEFUNCTIONS__INCLUDE__
#define MyLib__FREEFUNCTIONS__INCLUDE__

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

// Check if 'str' is null, empty or consists only of white-space characters. 
inline bool IsNullOrWhiteSpace(string str);

// More functions
[ ... ]

#endif

及源码:

#include "FreeFunctions.h"

inline bool IsNullOrWhiteSpace(string str)
{
    return (str.empty() || (str.find_first_not_of(' ') == string::npos));
}

我在一个类中使用这个函数:

#include "ConvertToOwnFormat.h"
#include "FreeFunctions.h"

ConvertToOwnFormat::ConvertToOwnFormat()
{
}


ConvertToOwnFormat::~ConvertToOwnFormat()
{
}

vector<Entry> ConvertToOwnFormat::ReadCatalogue(string path)
{
    if (!IsNullOrWhiteSpace(path)
    {
        [ ... ]
    }
}

我在ConvertToOwnFormat::ReadCatalogue 中收到以下错误:

错误 LNK2019 外部符号 "bool __cdecl IsNullOrWhiteSpace(class std::basic_string,类 标准::分配器 >)" (?IsNullOrWhiteSpace@@YA_NV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) 函数“public: class std::vector > __cdecl”引用的未解析 ConvertToOwnFormat::ReadCatalogue(class std::basic_string,class std::allocator >)" (?ReadCatalogue@ConvertToOwnFormat@@QEAA?AV?$vector@VEntry@@V?$allocator@VEntry@@@std@@@std@@V?$basic_string@DU?$char_traits@D@std@@V? $allocator@D@2@@3@@Z) MyProjectLib D:\Fuentes\Repos\MyProject\MyProjectLibConsoleTest\ConsoleMyProjectLib\Lib.lib(ConvertToOwnFormat.obj) 1

【问题讨论】:

  • 我可能是错的,但我相信内联通常用于在标头中声明方法,而不是在 cpp 文件中。你试过这个吗?
  • 是的,我试过了,它可以链接。谢谢。
  • 这不是问题,但是包含两个连续下划线 (MyLib__FREEFUNCTIONS__INCLUDE__) 的名称和以下划线后跟大写字母的名称保留给实现。不要使用它们。
  • 这也不是问题,但不鼓励标题内的using namespace (stackoverflow.com/questions/5849457/…)
  • 非常感谢您的 cmets。我正在学习,非常感谢他们。

标签: c++


【解决方案1】:

您必须将方法声明放在标题中。 inline 告诉编译器它应该用函数核心替换函数调用。因此,它需要在编译时为每个使用它的编译单元提供它

#ifndef MyLib__FREEFUNCTIONS__INCLUDE__
#define MyLib__FREEFUNCTIONS__INCLUDE__

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

// Check if 'str' is null, empty or consists only of white-space characters. 
inline bool IsNullOrWhiteSpace(std::string str)
{
    return (str.empty() || (str.find_first_not_of(' ') == std::string::npos));
}

// Others functions, prototype, ...

#endif

或删除源文件和头文件中的inline


这完全是题外话,但是从不在标题中放置using namespace:标题应该提供一些东西,但不应该强加命名空间之类的东西。另见"using namespace" in c++ headers

【讨论】:

    猜你喜欢
    • 2016-06-08
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多