der*_*kie 6 c++ static-libraries
我今天遇到了一个我不完全理解的行为。我直接跳到一个最小的代码示例中,并会在此过程中进行解释。
我有 2 个项目:一个静态 C++ 库和一个控制台应用程序。
静态库项目:
图书馆.h
#pragma once
namespace foo
{
int testFunc();
class StaticLibClass
{
public:
static int testMemberFunc();
};
}
Run Code Online (Sandbox Code Playgroud)
库.cpp
#include "Library.h"
using namespace foo;
// just some functions that don't do much
int testFunc()
{
return 10;
}
int StaticLibClass::testMemberFunc()
{
return 11;
}
Run Code Online (Sandbox Code Playgroud)
控制台应用项目:
主程序
#include "library.h"
using namespace foo;
void main()
{
// calling this function reslts in LNK2019: unresolved external symbol...
testFunc();
// this function works just fine
StaticLibClass::testMemberFunc();
}
Run Code Online (Sandbox Code Playgroud)
如您所见,类的静态成员函数工作正常。然而,单个 testFunc 会导致链接器错误。为什么是这样?
该问题的解决方案是不要在 Library.cpp 文件中使用“using”,而是将其包装在命名空间中,如下所示:
解决问题的更改:
库.cpp
#include "Library.h"
namespace foo
{
// just some functions that don't do much
int testFunc()
{
return 10;
}
int StaticLibClass::testMemberFunc()
{
return 11;
}
}
Run Code Online (Sandbox Code Playgroud)
您要么需要将实现函数/方法的主体包装在与原始标头匹配的命名空间语句中,要么您可以使用完全限定的名称,这可能是更好的 C++ 风格:
#include "Library.h"
// just some functions that don't do much
int foo::testFunc()
{
return 10;
}
int foo::StaticLibClass::testMemberFunc()
{
return 11;
}
Run Code Online (Sandbox Code Playgroud)
您不需要 using 命名空间 foo;在这个版本中。在实现这两个方法的主体时,您已经在命名空间 'foo' 中,但根据该命名空间中的其他类型,它可能很方便。