Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dll using gcc compiler/Mingw for visual basic?

Tags:

gcc

mingw

dll

How to create dll using gcc compiler/Mingw for visual basic?

like image 323
Rina Avatar asked Oct 19 '25 14:10

Rina


2 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)

like image 88
mmorris Avatar answered Oct 22 '25 06:10

mmorris


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.

like image 29
user877329 Avatar answered Oct 22 '25 05:10

user877329