longack
longack

Reputation: 115

cannot call function from a dll

The question is that my compiler cannot resolved a function from a dll file

Here is my library code

#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; 
}

My source code

#include "DllSample.h"

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

I config it like enter image description here

It will work if I put the function inline in the head file but when I do it above will fail to build.

The message is:

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)

Upvotes: 1

Views: 808

Answers (1)

robthebloke
robthebloke

Reputation: 9672

You are not marking the method (or class) as dllexport/dllimport. In your DLL project settings, make sure COMPILING_MY_DLL is defined. Assuming the paths to the DLL are correct when running the app, everything should work fine.

#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

Upvotes: 1

Related Questions