Create a DLL in C and link it to a C ++ project

As in the title, I am trying to create a DLL using C and associate it with a C ++ project. I read and followed various textbooks on the Internet, but every time something is missing, and I do not understand that.

Here is what I did, step by step:

I created a new Win32 project called testlib, then from the wizard I selected "DLL" and "Empty project".

Added caption:

//testlib.h

#include <stdio.h>

__declspec(dllexport) void hello();

Added source; since I want it to be the source of C that I read, I should just rename the .cpp file to .c, so

//testlib.c

#include "testlib.h"

void hello() {
    printf("DLL hello() called\n");
}

Designed by.

Now I would like to use my useful dll in another project.

Then: new project ( testlibUse). This time I selected "Empty project".
No need to add header, just create cpp source

//main.cpp
#include <testlib.h>

int main() {
    hello();
}

Then:

  • , testlib.dll "- > V++" โ†’ " "

  • , testlib.h โ†’ V++ โ†’

  • testlib.lib ( ) - > Linker- > Input- > Additional dependencies

, :

LINK: C:\path\testlibUse\Debug\testlibUse.exe ;
main.obj: LNK2019: "void __cdecl hello (void)" (? hello @@YAXXZ), _main
C:\path\testlibUse\Debug\testlibUse.exe: LNK1120: 1

testlib, testlib.c testlib.cpp dll, testlibUse, "dll not found".

"Release" ( , ), .

, , , .

?

, - , , DLL Qt?

+5
4

:

  • , DLL, .
  • extern "C" ++, , .
  • DLL , .

(1) (2), :

#ifdef __cplusplus
extern "C" {
#endif

// Assume this symbol is only defined by your DLL project, so we can either
// export or import the symbols as appropriate
#if COMPILING_MY_TEST_DLL
#define TESTLIB_EXPORT __declspec(dllexport)
#else
#define TESTLIB_EXPORT __declspec(dllimport)
#endif

TESTLIB_EXPORT void hello();
// ... more function declarations, marked with TESTLIB_EXPORT

#ifdef __cplusplus
}
#endif

(3), DLL , . " ", , DLL - . MSDN , DLL. DLL , . post-build , .

+9

extern "C" include:

extern "C" {
    #include <testlib.h>
}
+2

, , mangle cpp. extern "C" testlib.h:

#ifdef __cplusplus
extern "C"
#endif
__declspec(dllexport) void hello();
+1

C, ++. TESTLIB_EXPORTS DLL. , DLL, , .

__cplusplus , C ++.

#include <stdio.h>

#ifdef TESTLIB_EXPORTS
#define TESTLIB_API __declspec(dllexport)
#else
#define TESTLIB_API __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C" {
#endif

TESTLIB_API void hello();
/* other prototypes here */

#ifdef __cplusplus
}
#endif
+1

All Articles