Create DLL from unmanaged C++

心不动则不痛 提交于 2019-12-05 10:31:55

Unfortunately, I cannot help you with the managed code part, but this is how you create a DLL in CMake:

First of all, instead of using

`ADD_EXECUTABLE( YourLib SHARED yourclass.cpp yourclass.h )` 

in your CMakeLists.txt, use

`ADD_LIBRARY( YourLib SHARED yourclass.cpp yourclass.h )`

This will configure the solution to create a DLL rather than an executable.

However, to be able to use this DLL with your projects, you need to export the symbols you want to use. To do this, you need to add __declspec( dllexport ) to your class and/or function declarations. Building the library will then yield two files, a .dll and a .lib. The latter one is the so-called import library that you need when you want to use this library in your other projects. The .dll will be required at runtime.

However: When you want to use your library, you need to use __declspec( dllimport) (rather than dllexport). To avoid using two header files, the usual way to do this is to use the preprocessor. CMake actually helps you by providing a YourLibrary_EXPORTS define in your library project.

To summarize:

#ifndef YOUR_CLASS_H
#define YOUR_CLASS_H

#ifdef YourLib_EXPORTS
#define API_DECL __declspec( dllexport )
#else 
#define API_DECL __declspec( dllimport )
#endif

class APIDECL YourClass  {
   void foo();
   void bar();
};

#endif // YOUR_CLASS_H

EDIT: If you want to be able to use those functions from C (and languages that are able to use C functions) you should wrap your declarations with extern "C" {

extern "C" {
    API_DECL void myFirstFunction();
    API_DECL void mySecondFunction();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!