Search code examples
c++.netdllimportunmanagedlnk2019

LNK2028 and LNK2019 error when using dll with no inline code


This is the first time I'm using .NET and its giving me hard time when using more than one project. What am I doing wrong? This is what I did:

1 Create a new project (and solution). A "Class Library" called "Lib".

2 Add file "Comp1.h" to "Header Files" with the following code:

#ifndef COMP1_H
#define COMP1_H
class comp1
{
public:
    comp1(void);
    ~comp1(void);
}
#endif

3 Add file "Comp1.cpp" to "Source Files" with the following code:

#include "stdafx.h"
#include "Comp1.h"
comp1::comp1(void){}
comp1::~comp1(void){}

4 I overwrite the code of the automatically created "Lib.h" file with:

#ifndef LIB_H
#define LIB_H
#include "Comp1.h"
#endif

5 Add a "CLR empty project" called "Test" and set it as start-up project.

6 Add file "test.cpp" to "Source Files" of the "Test" project with the following code:

#include "../Lib/Lib.h"
#using "../Debug/Lib.dll"//Is this line mandatory?
int main()
{
comp1 component;
return 0;
}

7 Add "Lib" as a reference in the "Test" properties.

8 Make sure in "Project Dependencies" that "Test" depends on "Lib".

9 Compile them both as /clr

This is what I get:

1>test.obj : error LNK2028: unresolved token (0A000009) "public: __thiscall comp1::comp1(void)" (??0comp1@@$$FQAE@XZ) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)
1>test.obj : error LNK2028: unresolved token (0A00000A) "public: __thiscall comp1::~comp1(void)" (??1comp1@@$$FQAE@XZ) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)
1>test.obj : error LNK2019: unresolved external symbol "public: __thiscall comp1::~comp1(void)" (??1comp1@@$$FQAE@XZ) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)
1>test.obj : error LNK2019: unresolved external symbol "public: __thiscall comp1::comp1(void)" (??0comp1@@$$FQAE@XZ) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)

If I create inline functions this problem doesn't occur.

On forums you find answers about mistakes with including files, but I'm pretty sure I coded everything correct.

Thank you.


Solution

  • When you create the DLL you have to explictly mark functions and classes you want to export using the __declspec(dllexport) directive and thus make them available for import by a client. When you import the class you have to use the __declspec(dllimport) directive.

    This document shows how to mark classes and global functions in your headers so, that they can be used for export and import.