How to use GCC to build DLL by DEF file in MinGW?
The “How to generate DLL files by GCC in the MinGW” has described how to generate DLL file by the declaring prefix(__declspec( dllexport ) or __declspec( dllimport )) of functions + GCC tools(GCC, pexports). In normal case, it is enough to cater for the user requirements, but if users want to add anonymous functions or change the calling conventions(__stdcall, __cdecl, __pascal), how to do?
DEF file can play a role of these requirements. Firstly, let’s understand the format of DEF.
LIBRARY DllName.dll EXPORTS [__stdcall/__cdecl/__pascal]DllFunction[@BytesOfParamList] @SlotNumber … IMPORTS OtherDllName.OtherDllFunction … |
--- LIBRARY section indicates the name of DLL.
--- EXPORTS section lists the functions of interface in the DLL.
--- IMPORTS section describes the dependence of this DLL, such as these functions of other DLL.
--- [Options] they are optional, and can be ignored.
--- SlotNumber is a number of slot, and increase from 1 to the number of your functions
Ok, let’s show an example to make it clear.
1. Edit hello.def
1 LIBRARY hello.dll 2 EXPORTS 3 MyDllSay @1 4 hello = MyDllSay @2 |
Herein, hello is an anonymous function of MyDllSay, and can be invoked by other program.
2. Edit hello.c
1 #include <stdio.h> 2 3 void MyDllSay( void ) 4 { 5 printf( "I am a DLL function generated by GCC in the MinGW environment./n" ); 6 } 7 |
3. Build DLL
$ gcc -c -O3 hello.c $ dllwrap.exe --def hello.def -o hello.dll hello.o --output-lib libhello.a $ lib.exe /machine:i386 /def:hello.def /out:hello.lib |
dllwrap.exe produces a DLL by a DEF file. Readers input “dllwrap.exe --help” to acquire its usage. In fact, it depends gcc, ld and dlltool to fulfill its tasks.
4. Test DLL
a) Edit test.c
1 #include <stdio.h> 2 3 extern void hello( void ); 4 5 int main( void ) 6 { 7 hello(); 8 9 return 0; 10 } |
b) Compile and Execute it
1) Use GCC $ gcc -o test test.c -L./ -lhello $ ./test.exe I am a DLL function generated by GCC in the MinGW environment. |
2) Use VC $ cl test.c -link hello.lib $ ./test.exe I am a DLL function generated by GCC in the MinGW environment. |
[Summarization]
1. It is a complementary method for “How to generate DLL files by GCC in the MinGW”. To some extents, it looks more flexible, and programmers needn’t add prefix(__declspec( dllexport ) or __declspec( dllimport )) in the header file. Each function is easy to be exported or hidden in the rule of DEF file.
2. Anonymous function can be used. Users can follow their naming rules when calling these functions.
3. __stdcall, __cdecl and __pascal calling convention are available. It is agile for programmer to cross the different programming language with the help of prefix. I prefer __stdcall when DLL is generated^_^.