代码之家  ›  专栏  ›  技术社区  ›  Tsikon

内联函数的未解析符号

  •  -1
  • Tsikon  · 技术社区  · 7 年前

    请考虑以下代码:

    测试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错误(未解析的外部符号\u Foo)。 我可以用两种方法解决它。

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

    假设我希望将此函数内联,为什么我必须将extern添加到声明中?

    我使用VS2008。

    谢谢

    1 回复  |  直到 7 年前
        1
  •  2
  •   Daniel Langr    7 年前

    C++11标准段落3.2.3:

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

    您有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公司 到头文件中?如果编译器看不到代码,则无法内联它的代码。