Printer-friendly version

Exporting a class from a DLL for multiple instantiations

Implementing a class in a DLL allows for exchanging a component of a system without affecting the remainder of it. Exporting a class from a DLL using an abstract interface has been variously documented, but multiple instantiations using that setup have not. Widely referenced is Alex Blekhman's article at the Code project (http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL). While this works well for single instantiations, it does not work at all for various compilers, including MinGW's C++ compiler, when multiple instances are needed.

HOWTO Create and Deploy a Sample DLL using MinGW

A sample DLL

The DLL we will build will consist of a single source file "example_dll.cpp":

#include <stdio.h>
#include "example_dll.h"

__stdcall void hello(const char *s)
        printf("Hello %s\n", s);
int Double(int x)
        return 2 * x;
void CppFunc(void)
void MyClass::func(void)

The following header "example_dll.h" declares the interface of the DLL, and is used both when building the DLL and when building an executable that uses the DLL:


  1. ifndef EXAMPLE_DLL_H

HOWTO Create an Import Library for a DLL using MinGW

This page is about how to "call into" an existing DLL, using your mingw program. for information on creating your own DLL library, see DLL.

Usually (read: for all DLLs created with MinGW and also a few others) MinGW links fine against a DLL. No special import library is necessary (see sampleDLL).

However there are situations when it won't. Then one needs a so-called import library to help the linker. The rest of this page gives hints as to how to create such import libraries when there is only the DLL available.


TODO: Reformat to new wiki syntax.

!!! [Minimalist GNU for Windows | http://www.mingw.org]

!! MSVC and MinGW DLLs

Assume we have a testdll.h, testdll.c, and testmain.c. In the first case, we will compile testdll.c with MinGW, and let the MSVC-compiled testmain call it. You should use

gcc -shared -o testdll.dll testdll.c -Wl,--output-def,testdll.def,--out-implib,libtestdll.a

to produce the DLL and DEF files. MSVC cannot use the MinGW library, but since you have already the DEF file you may easily produce one by the Microsoft LIB tool:


Site Status

Site maintenance completed May 25th, 2012 at 12:38 UTC