首页 > 解决方案 > 无法从 dll 调用函数

问题描述

问题是我的编译器无法从 dll 文件中解析函数

这是我的图书馆代码

#ifndef DLL_SAMPLE
#define DLL_SAMPLE

#include <iostream>

class A
{
public:
    static void a();
};

#endif
#include "DllSample.h"

void A::a()
{
    std::cout << "hello, world" << std::endl; 
}

我的源代码

#include "DllSample.h"

int main(int argc, char* argv[])
{
    A::a();
    return 0;
}

我像这样配置它 在此处输入图像描述

如果我将函数内联在头文件中,它将起作用,但是当我在上面这样做时将无法构建。

消息是:

1>    main.obj : error LNK2019: unresolved external symbol "public: static void __cdecl A::a(void)" (?a@A@@SAXXZ) referenced in function _main
1>    D:\Home\Document\Visual Studio 2019 Projects\ErrorShot\Debug\CallDllFunctionSample.exe : fatal error LNK1120: 1 unresolved externals
1>    The command exited with code 1120.
1>  Done executing task "Link" -- FAILED.
1>Done building target "Link" in project "CallDllFunctionSample.vcxproj" -- FAILED.
1>
1>Done building project "CallDllFunctionSample.vcxproj" -- FAILED.
1>
1>Build FAILED.
1>
1>main.obj : error LNK2019: unresolved external symbol "public: static void __cdecl A::a(void)" (?a@A@@SAXXZ) referenced in function _main
1>D:\Home\Document\Visual Studio 2019 Projects\ErrorShot\Debug\CallDllFunctionSample.exe : fatal error LNK1120: 1 unresolved externals
1>    0 Warning(s)
1>    2 Error(s)

标签: c++dynamic-library

解决方案


您没有将方法(或类)标记为 dllexport/dllimport。在您的 DLL 项目设置中,确保定义了 COMPILING_MY_DLL。假设运行应用程序时 DLL 的路径是正确的,那么一切都应该正常工作。

#ifndef DLL_SAMPLE
#define DLL_SAMPLE

#ifdef COMPILING_MY_DLL
# define MY_DLL_EXPORT __declspec(dllexport)
#else
# define MY_DLL_EXPORT __declspec(dllimport)
#endif

#include <iostream>

class A
{
public:
    MY_DLL_EXPORT static void a();
};

#endif

推荐阅读