How to create dll using gcc compiler/Mingw for visual basic?
4 Answers
The following is how I was able to get MinGW to build a DLL to be used in Excel 2003 VBA.
fooBar.cpp
int __stdcall Foo(int x)
{
return x * x;
}
double __stdcall Bar(double x)
{
return x * x;
}
1) Start MinGW shell and create a directory called fooBar
.
Close the Excel Workbook (if open).
mkdir -p fooBar
cd fooBar
rm *.a *.dll *.def
2) Compile and generate a .def file - Note: this dll will not work because it has mangled symbols.
gcc -shared -o fooBar.dll fooBar.cpp -Wl,--output-def,fooBar.def,--out-implib,libfooBardll.a
The generated fooBar.def will look something like:
EXPORTS
_Z3Bard@8 @1
_Z3Fooi@4 @2
3) Modify the generated fooBar.def file by adding clean symbol aliases for the generated symbols. fooBar.def should now look something like:
EXPORTS
_Z3Bard@8 @1
_Z3Fooi@4 @2
Bar = _Z3Bard@8
Foo = _Z3Fooi@4
4) Cleaup again (except for the modified fooBar.def)
rm *.a *.dll
5) Compile with .def file with clean symbol aliases for the generated symbols.
gcc -shared -o fooBar.dll fooBar.cpp fooBar.def -Wl,--out-implib,libfooBar_dll.a
6) Open Excel and add the following VBA code (make sure to use the proper path, doubt it will have mmorris in it):
Private Declare Function Foo Lib _
"C:\MinGW\msys\1.0\home\mmorris\fooBar\fooBar.dll" _
(ByVal x As Long) As Long
Private Declare Function Bar Lib _
"C:\MinGW\msys\1.0\home\mmorris\fooBar\fooBar.dll" _
(ByVal x As Double) As Double
7) If you want to call the functions from an Excel Workbook, in a cell type =Foo(5)
or =Bar(5)

- 4,006
- 3
- 27
- 29
First some DLL-iquette:
All exported function should have C linkage. All C++-exceptions thrown inside the DLL should be catched inside the dll.
Why? Because there is no standard C++ ABI on Windows.
Also use __declspec(dllexport) on functions that should be exported
Now how to make the DLL without needing any DEF file
fooBar.cpp
#ifdef __cplusplus
extern "C"
{
#endif
__declspec(dllexport) int __stdcall square_int(int x) //I prefer manual mangling in this case to support static polymorphism
{
return x * x;
}
__declspec(dllexport) double __stdcall square_double(double x)
{
return x * x;
}
#ifdef __cplusplus
}
#endif
compile using
gcc fooBar.cpp -shared -Wl,--kill-at -o fooBar.dll
Now you should be able to call square_xxx as in mmorris answer. His solution probably works though.

- 6,717
- 8
- 46
- 88
-
This compiled, but it did not work in Excel. The advice by mmorris works, but this looks like a better implementation. Perhaps a version of mingw gcc version problem? This method is something I should beat my head over because it appears to be a more elegant solution. Thanks. – RJB Mar 28 '13 at 17:50
-
@RJB I have not tried my self, but perhaps excel does not recognize '_' – user877329 Mar 31 '13 at 08:48
VB (all versions) prefers the pascal calling convention.
Declare your external functions with WINAPI and export them in your .def file.

- 40,822
- 8
- 72
- 132