Creating DLLs with MinGW 17 Sep, 2008 Creating DLLs with MinGW

This morning, I was asked how to use existing C code in C++ code. So I took the route of converting the C code into a DLL and then linking to it from the C++ code. So I had to figure out how to do this using MinGW on Windows. Here is an account of my experiments (distilled ofcourse!):
There are three things you need to do:
1. Convert the existing into a DLL.
2. Include the header of the DLL in the sources where you wish to use the library.
3. Build your code, linking against your DLL.

Here are the steps:
a) For this, you need to add the following code to the header file containing the declarations of the functions that are to be used:

#ifdef cplusplus
#define cppfudge "C"
#else
#define cppfudge
#endif

#ifdef BUILD_DLL
// the dll exports
#define EXPORT
declspec(dllexport)
#else
// the exe imports
#define EXPORT extern cppfudge __declspec(dllimport)
#endif

b) Front of each function that you want to use from the DLL, prepend the word EXPORT. For example:
EXPORT int hello(void);

c) Create the create the object code using the following command:
>gcc -c -DBUILD_DLL TestDLL.c, where TestDLL.c is the source file.

d) Next, use the object code to create the DLL with the following command:
>gcc -shared -o TestDLL.dll TestDLL.o -Wl,--out-implib,TestDLL.a, Note that TestDLL has to be replaced with whatever is the actual DLL name.
>Creating library file: TestDLL.a (This is the output of the command)

e) Now, compile the actual file (note that this file should include the TestDLL.h header)
>gcc Main.cpp -o Main.exe TestDLL.dll

f) Done! Run the executable:
>Main.exe
Hello World!

>

Here are the files that I have used to test these things. I have tested them on Windows XP using MinGW32. I have used the following link for reference: http://www.emmestech.com/moron_guides/moron2.html



Tags  ·   Show Comments ▾


     
Original design for Tumblr crafted by Prashanth Kamalakanthan.
Adapted for Tumblr & Jekyll by Sai Charan. Customized theme available on Github.

Sai Charan's blog by Sai Charan is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
Creative Commons License