无法从动态库 (dll) C++ [重复] 导入所有类

Can't import all class from dynamic library (dll) C++ [duplicate]

提问人:J3hud 提问时间:6/5/2023 更新时间:6/5/2023 访问量:48

问:

我有两个类要从动态库导入。一次,然后工作就好了。我可以使用第一个而不会出现任何链接错误,但第二个会创建链接 2019 代码错误。我不知道我做错了第二个。

只有当我尝试使用该类时,才会发生问题。

有头文件和定义,创建链接错误:

Vertice.h //the class with linking error

#pragma once

#ifdef CGENGINE_EXPORTS
#define ENGINE_API __declspec(dllexport)
#else
#define ENGINE_API __declspec(dllimport)
#endif

constexpr char EMPTYCHAR = char(32);

class ENGINE_API Vertice
{
public:
    Vertice(int color, char caracter);
    ~Vertice(void);
    const bool operator != (const Vertice vertice);

public:
    int color;
    char caracter;
};

Vertice.cpp

#include "Vertice.h"

Vertice::Vertice(int color, char caracter) :
    color(color), caracter(caracter)
{
}

Vertice::~Vertice(void)
{
}

const bool Vertice::operator!=(const Vertice vertice)
{
    const unsigned int size = sizeof(Vertice);
    for (int index = 0; index < size; index++)
    {
        char* self_byte = ((char*)this) + index;
        char* vertice_byte = ((char*)&vertice + index);

        if (*self_byte != *vertice_byte) { return false; }

    } return true;
}

有错误输出:

Build started... 1>------ Build started: Project: Flappy Bird, Configuration: Debug Win32 ------ 1>Application.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall Vertice::Vertice(int,char)" (__imp_??0Vertice@@QAE@HD@Z) referenced in function _main 1>Application.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall Vertice::~Vertice(void)" (__imp_??1Vertice@@QAE@XZ) referenced in function _main 1>C:\Users\Jehud\source\repos\CGEngine\Debug\Flappy Bird.exe : fatal error LNK1120: 2 unresolved externals 1>Done building project "Flappy Bird.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ========== Build started at 9:22 PM and took 02,122 seconds ==========

我尝试将两个类声明放在同一个头文件和/或同一个cpp文件中。它给了我相同的错误输出。

C++ DLL LNK2019

评论

0赞 Ken Y-N 6/5/2023
请指出您是如何编译和链接文件的 - dup 用于命令行问题,但也许您正在使用 IDE?
0赞 J3hud 6/5/2023
我使用视觉代码 2022,我已经检查了两边的项目属性,一切都很好。
0赞 n. m. could be an AI 6/5/2023
拥有 IDE 并不能神奇地使您的工作没有错误。显示实际的编译和链接命令。

答:

-1赞 daniyar 6/5/2023 #1

根据本文档在 C++ 类中使用 dllimport 和 dllexport,必须使用下一个类声明:

#define DllExport   __declspec( dllexport )

class DllExport C {
   int i;
   virtual int func( void ) { return 1; }
};