c++ - 链接具有内联函数的静态库时出现问题

标签 c++ linker inline static-libraries

我有一个静态库,它(除其他外)实现了一个小函数,该函数仅从常量字符串表中返回一些字符串。该函数不会在库内的任何地方调用,但仍被声明为内联。为了清楚起见,它看起来像这样:

namespace flow
{
    inline const char* GetName( BYTE methodType );
}

以及实现:

const char* flow::GetName( BYTE methodType )
{
    if ( methodType < 5 )
        return cszNameTable[ methodType ];

    return NULL;
}

在另一个项目中,我链接到这个库。我包含正确的 .h 文件,并且我的代码中有 using namespace flow; 。问题是,我收到链接器错误:

error LNK2001: unresolved external symbol "char const * __cdecl flow::GetName(unsigned char)" (?GetName@flow@@YAPBDE@Z)

现在我可以通过从静态库的函数声明中删除“inline”关键字来轻松解决这个问题。这是我的问题:

1) 为什么会出现此错误?如何在不修改静态库源代码(不删除 inline 关键字)的情况下修复它?

2)不在库本身内部调用的静态库函数中使用inline关键字有什么好处?当链接到另一个项目的库时,inline 关键字是否有任何效果(我猜有,但我不确定)?

最佳答案

1) Why does this error appear? How can i fix it without modifying the static library source code (without removing the inline keyword)?

将函数声明内联是没有意义的。无论如何,您都必须在 header 中定义它们:

namespace flow
{
    inline const char* GetName( BYTE methodType )
    {
        if ( methodType < 5 )
            return cszNameTable[ methodType ];

        return NULL;
    }
}

2) What is the benefit of using the inline keyword in a static library function that is not called inside the library itself? Does the inline keyword have any effect when linking against the library from another project (i guess it does, but i'm not sure)?

内联的效果是您可以并且必须在 header 中定义该函数,因为实现 内联 函数的调用位置必须可见

关于c++ - 链接具有内联函数的静态库时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3203365/

相关文章:

c++ - 链接到G++中的复数库

macos - 链接器在链接时是否生成绝对虚拟地址

php内联回调

c-preprocessor - 什么是 _LIBCPP_INLINE_VISIBILITY?

c++ - 找出一个表达式来评估一个循环

c++ - 如何使用 <format> header

c++ - Qt 编译问题 w/MySQL - Mac OS X

c++ - makefile 链接不起作用(尽管没有错误消息)

c++ - 静态 constexpr 变量是否在 C++ 中内联?

c++ - 从基类指针克隆派生类