C++ 未解析的外部符号(LNK2019)
我有以下文件:C++ 未解析的外部符号(LNK2019),c++,visual-studio-2008,linker,C++,Visual Studio 2008,Linker,我有以下文件: 接口.h class Interface { ... }; Interface* CreateInterface(); impl.h #include "interface.h" class Impl: public Interface { ... }; impl.cpp #include "impl.h" SomeInterface* CreateInterface() { return new Impl; } ... main.cpp #include
接口.h
class Interface
{
...
};
Interface* CreateInterface();
impl.h
#include "interface.h"
class Impl: public Interface
{
...
};
impl.cpp
#include "impl.h"
SomeInterface* CreateInterface()
{
return new Impl;
}
...
main.cpp
#include "Interface.h"
int main()
{
CreateInterface();
}
最初我的项目看起来很受欢迎。但出于测试目的,所有文件现在都在同一个项目中。编译时,我收到LNK2019错误,表示CreateInterface未解决。我使用的是VS 2008,我不知道出了什么问题。链接器告诉您它知道
CreateInterface
存在并且是一个函数,但它找不到实际的函数本身。因此,我怀疑您的项目中没有包含impl.cpp,而且它也没有得到编译。您是否打算有多个CreateInterface()
声明
接口.h
Interface* CreateInterface();
Impl.cpp
SomeInterface* CreateInterface()
Interface* CreateInterface() // note the return type
{
return new Impl;
}
其中只有一个(后者)似乎得到了实际实施。您的名称不明确,编译器似乎选择了错误的名称(很可能是因为它不知道另一个名称是否存在)
在impl.cpp中定义CreateInterface()
,参数列表和返回类型与Interface.h中的原型相同。我通常不会宽恕这样一个兽性的设计,但这似乎是你想要的
Impl.cpp
SomeInterface* CreateInterface()
Interface* CreateInterface() // note the return type
{
return new Impl;
}
老实说,我甚至不能相信这是编译的,考虑到这两者之间的唯一区别(Interface.h中的声明和Impl.cpp中的实现)是返回类型的差异,编译器应该对此感到恶心,所以很可能有些东西你还没有给我们看。你确定
impl.cpp
已经编译好了吗?你确定没有拼错函数名吗?@LuchianGrigore没有拼错。至于确保它被编译,我该怎么做?我所知道的是,如果我把一个文件放在解决方案的源文件部分,它应该会自动编译。添加一些不应该在文件中编译的伪代码怎么样。只需放置一行这不应该编译源代码中的代码>。如果没有错误,它就不会被编译。Getting error,所以它正在被编译。我想到一件事:是main.cpp
包括正确的接口.h
?在完整的LNK2019错误中,链接器正在查找的CreateInterface
的签名和限定是否与impl.cpp
中的签名和限定匹配?这是一个打字错误,但发现它很好:)