angryInsomniac
angryInsomniac

Reputation: 859

Virtual functions with trivial definitions in cpp file causing linker errors

So, I have two projects , project 2 builds to a dll where I have this class (header and cpp follow)

header

class classWvirts
{
    public:
    classWvirts(){};
   ~classWvirts(){};

    virtual int testVirtualFunction();
};

cpp

#include "classWvirts.h"

int classWvirts::testVirtualFunction()
{
    return 1;
}

In project 1 (which builds to an exe) I just have a .cpp file that looks like this :

#include "../testApp2/classWvirts.h"
classWvirts obj1;

int main()
{
    obj1.testVirtualFunction();
}

This setup seems to have all the ingredients for it to work, my method , though it is marked as virtual , has a trivial definition in its cpp file.

However, when I attempt to compile this , I get a LNK2001 Linker error that looks like

Error 1 error LNK2019: unresolved external symbol "public: virtual int __thiscall classWvirts::testVirtualFunction(void)" (?testVirtualFunction@classWvirts@@UAEHXZ) referenced in function _main E:\Work\Scratch\US1212_Virt\testApp\testApp\Source.obj testApp

Can someone please point out what I am doing wrong ? I realize that if I put the trivial definition inside the header file everything will work, but what if that is not an option ? (This is obviously a simplified version of a problem I have in a larger project) , there could be room for making the cpp into an inl and including it in the header, but I would rather avoid that and maintain my cpp and header distinction.

Upvotes: 0

Views: 246

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320371

When you are making a DLL with Visual Studio compiler, you have to export the class from the DLL library by declaring it with __declspec(dllexport) in the library

class __declspec(dllexport) classWvirts 
{
  ...

And the you have to import it in your main project by declaring it with __declspec(dllimport) in the main project

class __declspec(dllimport) classWvirts 
{

In order to use the same header file for both import and export, you can introduce a macro

#define MY_DLL_IMPORT_EXPORT ...

class MY_DLL_IMPORT_EXPORT classWvirts 
{
  ...

which you will define as __declspec(dllexport) when compiling the DLL and as __declspec(dllimport) in all other cases (i.e. when compiling the main project).

If you create a dependency of your main project on your DLL project, Visual Studio should take care of the other linker setting automatically (i.e. it will automatically link the main project with the import library of your DLL). If you don't have that dependency then either create it or manually specify the DLL import library in the linker settings of the main project.

Upvotes: 2

Related Questions