In addition to the mechanics of making a function call requiring matching calling conventions, which is fixed by giving the function pointer the correct type as described below, the calling convention affects name mangling.
extern "C"
prevents the C++ modus operandi of including the type into the name, so that overloads of a function get unique names and can be differentiated during symbolic lookup. But it doesn't prevent mangling entirely. For example, the function in the question, void __stdcall hello(void)
will be exported by __declspec(dllexport)
as _hello@0
, where the trailing number is the number of bytes in the argument list. This helps avoid the situation that the caller and callee disagree on the size of the arguments, which is particularly problematic in __stdcall
where the callee cleans up the stack.
Nevertheless, one can disable name mangling (and the Win32 DLLs such as gdi32.dll
and shell32.dll
have done so). For that you need a linker definitions file:
EXPORTS
hello
; or hello = _hello@0
The linker knows about the mangling rules and will find the mangled name in the object file even if you don't provide it explicitly.
Additionally, when the exports are listed in the definition file, you no longer need __declspec(dllexport)
in the code.
More information is available on MSDN.
If you call a function through a function pointer of the wrong type, you get undefined behavior. The calling convention is part of the type. Try:
typedef bool (APIENTRY *f_void)(void); // or __stdcall instead of APIENTRY
I would guess that one of your header files contains #define APIENTRY __stdcall
It's always a good idea to explicitly set the calling convention of exported functions and function pointers. If you don't, you get the currently effective default calling convention, which is a project-specific compiler option.
Pedantically, whether a function and function pointer is marked extern "C"
or not is also part of the type. But on Windows, where DLLs are found, extern "C"
and extern "C++"
have identical effect on calling convention.