I hear the DllMain function is called when the process loads the needed dll at the start time, so I write the following code to verify this:
//mydll.cpp #include <windows.h> BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: MessageBox(NULL, "DLL_PROCESS_ATTACH", "Message", MB_OK); break; case DLL_THREAD_ATTACH: MessageBox(NULL, "DLL_THREAD_ATTACH", "Message", MB_OK); break; case DLL_THREAD_DETACH: MessageBox(NULL, "DLL_THREAD_DETACH", "Message", MB_OK); break; case DLL_PROCESS_DETACH: MessageBox(NULL, "DLL_PROCESS_DETACH", "Message", MB_OK); break; } return TRUE; } int __declspec(dllexport) Sum(int a, int b) { return a + b; }
//app.cpp #include <iostream> using namespace std; int Sum(int a, int b); int main() { cout << Sum(5, 10); return 0; }
I use Mingw g++ to compile:
g++ -g -shared -o mydll.dll mydll.cpp g++ -g -o app.exe app.cpp mydll.dll
All are ok. Running app.exe outputs the desired 15. But when debugging app.exe, it never stops at the breakpoint set inĀ DllMain although I can step into the function Sum in the dll. Why isn’t DllMain called?
This is because the g++ compiler mangles the function name DllMain into other name which is not considered by the linker as the entry point for a dll. (This mangled function resides in the dll as an ordinary function.) The entry point is strictly the function named after “DllMain”. The cue is using extern “C” for DllMain:
//mydll.cpp #include <windows.h> extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: MessageBox(NULL, "DLL_PROCESS_ATTACH", "Message", MB_OK); break; case DLL_THREAD_ATTACH: MessageBox(NULL, "DLL_THREAD_ATTACH", "Message", MB_OK); break; case DLL_THREAD_DETACH: MessageBox(NULL, "DLL_THREAD_DETACH", "Message", MB_OK); break; case DLL_PROCESS_DETACH: MessageBox(NULL, "DLL_PROCESS_DETACH", "Message", MB_OK); break; } return TRUE; } int __declspec(dllexport) Sum(int a, int b) { return a + b; }