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:
- Convert the existing into a DLL.
- Include the header of the DLL in the sources where you wish to use the library.
- Build your code, linking against your DLL.
Here are the steps:
- 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
- Front of each function that you want to use from the DLL, prepend the word
EXPORT
. For example:
EXPORT int hello(void);
- Create the create the object code using the following command (where
TestDLL.c
is the source file):
> gcc -c -DBUILD_DLL TestDLL.c
- Next, use the object code to create the DLL with the following command (note that
TestDLL
has to be replaced with whatever is the actual DLL name):
> gcc -shared -o TestDLL.dll TestDLL.o -Wl,--out-implib,TestDLL.a
> Creating library file: TestDLL.a` # (this is the output of the command)
- Now, compile the actual file (note that this file should include the TestDLL.h header)
>gcc Main.cpp -o Main.exe TestDLL.dll
- 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.