静态指针对函数的未定义引用

Undefined reference to function from static pointer

我正在尝试在运行时加载 dll,但我遇到了一个问题:我有一个小助手 class,它在主程序中被分配。指向该对象的指针被传递给加载的 dll。为了测试它,我想从 class (printLine) 调用一个函数。但是我无法编译 dll,因为我得到了一个:

Utility.o: In function `ZN7Utility6onInitEv':
D:\Benutzer\Jan\Desktop\Programmierprojekte\Game Engine 5.0\Utilities\Debug/../Utility.cpp:7: undefined reference to `ModuleHelper::printLine(std::string)'
collect2.exe: error: ld returned 1 exit status

这两个文件是dll的唯一内容:

Utility.h:

#ifndef UTILITY_H_
#define UTILITY_H_

#include <iostream>
#include <Definitions.h>
#include <ModuleHelper.h>

class Utility
{
public:
    Utility();
    ~Utility();

    static void onInit();
    static void onUpdate();

    static char* getName();
    static char** getDependencies();
    static int getCountDependencies();
    static char* getServeAs();

    static void setModuleHelper(ModuleHelper* helper);

private:
    static constexpr char* name = "Utility";
    static constexpr char** dependencies = nullptr;
    static constexpr int countDependencies = 0;
    static constexpr char* serveAs = "";
    static ModuleHelper* moduleHelper;
};

extern "C" //GAME_API is a dllexport macro
{
    char* GAME_API getName()
    {
        return Utility::getName();
    }

    char** GAME_API getDependencies()
    {
        return Utility::getDependencies();
    }

    int GAME_API getCountDependencies()
    {
        return Utility::getCountDependencies();
    }

    char* GAME_API getServeAs()
    {
        return Utility::getServeAs();
    }

    noargfunc GAME_API onInit()
    {
        return Utility::onInit;
    }

    noargfunc GAME_API onUpdate()
    {
        return Utility::onUpdate;
    }

    void GAME_API setModuleHelper(ModuleHelper* moduleHelper)
    {
        Utility::setModuleHelper(moduleHelper);
    }
}
#endif /* UTILITY_H_ */

Utility.cpp:

#include "Utility.h"

ModuleHelper* Utility::moduleHelper; //with "= nullptr" or "= NULL" it didn't work either

void Utility::onInit()
{
    moduleHelper->printLine("Hello from Utilities"); //wrapper for std::cout
}

void Utility::onUpdate()
{

}

char* Utility::getName()
{
    return name;
}

char** Utility::getDependencies()
{
    return dependencies;
}

int Utility::getCountDependencies()
{
    return countDependencies;
}

char* Utility::getServeAs()
{
    return serveAs;
}

void Utility::setModuleHelper(ModuleHelper* helper)
{
    moduleHelper = helper;
}

未定义的引用意味着未找到实现。

看起来您只是为了使用该库而包含了头文件。

主要问题(linker 错误 - 不是运行时!)是您可能忘记了 link 库。 (Visual Studio 中的项目参考)

无论如何,如果您可以编译并且 link 您的代码,您会发现下一个错误。

ModuleHelper* Utility::moduleHelper; //with "= nullptr" or "= NULL" it didn't work either

如果您使用 NULL 初始化 moduleHelper,然后使用“->”取消引用指针并尝试执行某项操作,您将得到一个空指针异常。 您必须初始化它...(可能是 = new ModuleHelper)。由于我不知道使用的库,您必须自己阅读文档。