未解析的外部符号 _declspec(dllimport)

Kev*_*sen 6 c++ dll enums dllimport console-application

我在 Visual Studio 中为我的控制台应用程序创建了一个 DLL。在我的 DLL 中,我有一个名为 Dialog_MainMenu 的类,其中包含一个 *.cpp 文件和一个 *.h 文件。

以下错误消息

错误 9 错误 LNK2001: 未解析的外部符号 "__declspec(dllimport) public: static enum Dialog_MainMenu::GAME_STATES Dialog_MainMenu::CurrentGameState" (_ imp ?CurrentGameState@Dialog_MainMenu@@2W4GAME_STATES@1@A) C:\Users\Kevin\Desktop\ c++ projects\development_testing\The Intense Adventure\Dialogs\Dialog_MainMenu.obj Dialogs

我有点不明白。这只发生在我向头文件中的原型添加枚举时。

头文件

#ifdef DIALOG_MAINMENU_EXPORTS
#define DIALOG_MAINMENU_API __declspec(dllexport) 
#else
#define DIALOG_MAINMENU_API __declspec(dllimport) 
#endif

class Dialog_MainMenu {
public:
    static DIALOG_MAINMENU_API enum GAME_STATES {
        MAINMENU, GAME, OPTIONS, CREDITS, QUIT
    };
    static DIALOG_MAINMENU_API GAME_STATES CurrentGameState;
    DIALOG_MAINMENU_API GAME_STATES GetState();
};
Run Code Online (Sandbox Code Playgroud)

(不知道问题是否出在这里,所以我会添加它) 一般的cpp文件

//Get state
Dialog_MainMenu::GAME_STATES Dialog_MainMenu::GetState() {
 // Code..
}

//Switching state
Dialog_MainMenu::CurrentGameState = Dialog_MainMenu::GAME_STATES::GAME;
Run Code Online (Sandbox Code Playgroud)

我真的很感激,任何帮助或至少一些建议,我可以在那里了解更多关于这个问题的信息。

YK1*_*YK1 5

您需要在全局范围内的 cpp 文件中定义静态成员。

Dialog_MainMenu::GAME_STATES Dialog_MainMenu::CurrentGameState;
Run Code Online (Sandbox Code Playgroud)

或者,您也可以为其分配一些初始值。

Dialog_MainMenu::GAME_STATES Dialog_MainMenu::CurrentGameState = Dialog_MainMenu::GAME_STATES::GAME;
Run Code Online (Sandbox Code Playgroud)

编辑

我在 Visual Studio 中为我的控制台应用程序创建了一个 DLL。在我的 DLL 中,我有一个名为 Dialog_MainMenu 的类,其中包含一个 *.cpp 文件和一个 *.h 文件。

好的 - 当您编译 dll 时 - 您正在导出类型。因此,您需要dll 文件中的define静态成员.cpp。您还需要确保DIALOG_MAINMENU_EXPORTS在编译器设置中启用了定义。这将确保导出类型。

现在,当您将控制台应用程序与 dll 链接时 - 您将使用#includedll 的标头并且不启用DIALOG_MAINMENU_EXPORTS编译器设置中的任何定义(只需保留设置默认值)。这将使编译器了解您现在正在将类型从 dll 导入到控制台应用程序中。

我希望现在清楚了。


osy*_*ets 5

检查是否使用 .dll 添加了对项目的引用(它解决了我的问题)右键单击项目>添加>引用>(包含 .dll 的项目)

  • 即使六年后人们仍然发现这个问题可能会对某人有帮助! (3认同)