Patrizio Bertoni
Patrizio Bertoni

Reputation: 2712

Link a MSVC compiled DLL in a MinGW-built project

Given two C++ projects:

  1. a Win32 C++ project compiled as a x86 DLL under Visual Studio 2015
  2. a Qt GUI application using Desktop Qt 5.5.1 MinGW 32 bit Kit.

What I'm trying to do is to link the first one in the second one. A MWE follows.

DLL header file: libxspectra.h

namespace XSpectra
{
  #define LIBXSPECTRA_EXPORTS // already defined into Project Properties
  #ifdef LIBXSPECTRA_EXPORTS
  #define LIBXSPECTRA_API __declspec(dllexport)
  #else
  #define LIBXSPECTRA_API __declspec(dllimport)
  #endif

  LIBXSPECTRA_API int fnlibxspectra(void);
  LIBXSPECTRA_API int gnara(void) { return 7; };
  int foo() { return 1; };
  int bar();
}

DLL source file: libxspectra.cpp

#include "libxspectra.h"

namespace XSpectra
{
  LIBXSPECTRA_API int fnlibxspectra(void)
  {
    return 42;
  }

  int bar()
  {
    return 6;
  }
}

Qt source file: main.cpp

#include "libxspectra.h"

int main(int argc, char *argv[])
{
  XSpectra::foo();
  XSpectra::bar();
  XSpectra::gnara();
  XSpectra::fnlibxspectra();
  return 0;
}

Qt application build log

error: undefined reference to XSpectra::bar()

error: undefined reference to _imp___ZN8XSpectra13fnlibxspectraEv

While foo() and gnara() links correctly.

A few notes

  1. I know the problem is not strictly Qt-related, but it's a matter of different compilation toolchains, a field where I'm a real novice. I'm actually asking for advices on this way.
  2. If I comment the #define LIBXSPECTRA_EXPORTS, Visual Studio's Intellisense still marks it as defined, dll compiles, but the behaviour of external application's build process changes. The following error arises:

error: function 'int XSpectra::gnara()' definition is marked dllimport

Upvotes: 2

Views: 2666

Answers (1)

rubenvb
rubenvb

Reputation: 76519

You can only link MSVC compiled C DLLs with MinGW, and only on 32-bit Windows. The MinGW linker can link directly to the DLL (if the functions are properly exported and not only available through an import library) or the usual import library. See here and here for how to generate a MinGW import library from a DLL.

You'll do it just like with MSVC (compile the dll with the functions marked dllexport, and compile the code using the dll with the functions marked dllimport, or use a .def file or something). Remember you need to export C functions, which means they need to be marked extern "C".

I would strongly suggest though, making the code compatible with MinGW, and just compile everything with that. Or use the MSVC version of Qt.

Upvotes: 4

Related Questions