在两个项目之间链接时,获取虚拟函数的链接错误

Getting Link Errors with virtual functions when linking between two projects

本文关键字:链接 获取 函数 错误 虚拟 之间 项目 两个      更新时间:2023-10-16

我在一个项目中创建了一个基类和派生类,比如ConsolApp1,其中基类有几个虚拟方法和一个虚拟析构函数。这些方法都设置为纯虚拟方法,然后在派生类中定义这些方法,并使用override关键字进行重写。此外,派生类和基类都封装在命名空间中。当我创建一个新项目时,比如说名为ConsolApp2的项目,它与实现派生类对象的ConsolApp1位于同一解决方案中。对于任何声明为虚拟的方法或析构函数,都会出现链接错误。为了允许ConsolApp2包含派生类及其所在的命名空间,我必须添加头文件位置的路径。我确信我做得很好,因为当我试图包括它时,头文件会显示出来。提前感谢你的帮助。

以下是我遇到的问题的一些伪代码。我能够编译ConsolApp1而没有错误,但ConsolApp2没有构建并抛出三个链接错误,两个用于虚拟方法,一个用于虚拟析构函数。编译是使用VS2012完成的。错误为:

错误LNK2001:未解析的外部符号"public:virtual int const__thiscall FooSpace::FooDerived::GetSomething(void)const"(?GetSomething@FooDerived@FooSpace@@UBE?BHXZ)

错误LNK2001:未解析的外部符号"public:virtual void __thiscall FooSpace::FooDerived::SetSomething(int)"(?SetSomething@FooDerived@FooSpace@@UAEXH@Z)

错误LNK2019:未解析的外部符号"public:virtual__thiscall FooSpace::FooDerived::~FooDerived(void)"(??1FooDerived@FooSpace@@UAE@XZ)在函数"public:virtual void*__thiscall FooSpace::FooDerived::`标量删除析构函数'(unsigned int)"中引用(??_GFooDerived@FooSpace@@UAEPAXI@Z)

ConsolApp1:

FooBase.h

namespace FooSpace
{
    class FooBase
    {
        public:
            FooBase(){}
            virtual ~FooBase() {}
            virtual const int GetSomething() const = 0;
            virtual void SetSomething(int f) = 0;
    };
}

FooDerived.h

#include "FooBase.h"
namespace FooSpace
{
    class FooDerived : FooBase
    {
        public:
            FooDerived() : FooBase(){}
            ~FooDerived() override;
            const int GetSomething() const override;
            void SetSomething(int f) override; 
    };
}

FooDerived.cpp

#include "FooDerived.h"
FooSpace::FooDerived::~FooDerived()
{
    //destruct an object of FooDerived
}
const int FooSpace::FooDerived::GetSomething() const
{
    int ret = 0;
    return ret;
}
void FooSpace::FooDerived::SetSomething(int f)
{
    // Set some private variable equal to f
}

包含FooMain.cpp->以确保丢失的main()没有错误

#include "FooDerived.h"
using namespace FooSpace;
int main()
{
    FooDerived derivedObject;
    return 0;
}

ConsolApp2:

FooImplement.h

#include <FooDerived.h>
#include <vector>
using namespace std;
using namespace FooSpace;
class FooImpliment
{
    private:
        vector<FooDerived> fooVector;
    public:
        FooImpliment(void);
        ~FooImpliment(void);
        void SetFooVector(vector<FooDerived> newVector);

};

FooImplement.cpp

#include "FooImpliment.h"

FooImpliment::FooImpliment(void)
{
}

FooImpliment::~FooImpliment(void)
{
}
void FooImpliment::SetFooVector(vector<FooDerived> newVector)
{
    fooVector =  newVector;
}

包含ImplementMain.cpp->以消除丢失main()的错误

int main()
{
    return 0;
}

但是ConsolApp2不编译并且抛出三个链接错误。

错误,ConsolApp2.cpp编译。问题不在于编译,而在于linking

在你的项目中,你应该编译

  • FooDerived.cpp
  • FooImplement.cpp
  • ImplementMain.cpp

如果不是,请将缺少的模块添加到项目中。

在这种情况下,似乎是FooDerived.cpp没有被编译或不是VisualStudio项目的一部分。

相关文章: