MinGW dev

From miki
Jump to navigation Jump to search

This page is dedicated to MinGW development, ie. any development using the MinGW compiler toolchain (linux/msys/mingw) or platform (msys/mingw).

Tips

Create a DLL with MinGW and import it in Visual Studio

References:

The key points:

  • Make sure to use __declspec(dllexport) when creating the DLL, and __declspec(dllimport) when importing it.
  • Make sure to use __cdecl calling convention when exporting and importing the DLL (alternative is to use __std_call).
  • Make sure to add extern "C" declaration when compiling in C++. This is necessary to force "C" decl, which is the only compatible declaration between compilers.
  • Make sure to generate an import library, which is necesary / useful when importing the DLL in VS.

So, to create the DLL, we need declaration like these:

#ifdef      __cplusplus
extern "C" {
#endif

#if defined(__MINGW32__)
#ifdef BUILD_DLL
#define DLL_DECL  __declspec(dllexport)
#else
#define DLL_DECL  __declspec(dllimport)
#endif
#define DLL_CALL  __cdecl
#else
#define DLL_DECL
#define DLL_CALL
#endif

DLL_DECL int  some_exported_variable;
DLL_DECL int DLL_CALL  some_exported_fct(int x, int y);

#ifdef      __cplusplus
}
#endif

Then, to build the DLL, creating an import lib:

g++ -c -DBUILD_DLL example_dll.cpp
g++ -shared -o example_dll.dll example_dll.o -Wl,--out-implib,example_dll.lib

To import the DLL in Visual Studio, one must

  • Include the header file with same declaration as above.
  • Add to the project the import library (example_dll.lib). This is necessary to do the linking (or VS will complain of missing symbols).