Hello!

This content has been updated. You will be momentarily redirected to the current version.

Moved!



Moved! I now blog at http://www.saicharan.in



Wednesday, September 17, 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

1 comment:

Kruz said...

I created a series of small programs that I use for work everyday, and this is exactly what I was looking for, but it's not really dynamic.

For instance, if I wanted to load 'Richedit.DLL' and use it, I wouldn't have the header file to compile with. Also, if I wanted to create a VB program using the C++ insides and use VB for the GUI, I couldn't compile the VB program with a C++ header.

I found an example here: http://sig9.com/node/35
That shows both the Windows LoadLibrary function and the way you did it.

^_~ Your example will work great for me though.

Thanks!
-Kruz