I'm working on an existing c++ project with visual studio, and I found out that almost every function declaration gets a __cdecl
in front of the function name, like:void __cdecl functionName()
. Then I jump to the definition of __cdecl
, which locates in the winnt.h
file:
#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
#define NTAPI __stdcall
#else
#define _cdecl
#define __cdecl
#define NTAPI
#endif
I've searched cdecl and got that it's the default calling convention for C and C++ programs, but code above tells me that __cdecl
extends to nothing. So why place a __cdecl
before function name as it's just nothing ? or did I misunderstand the code above?
what's the meaning of #define __cdecl”
Lines that begin with #
are preprocessor directives. #define
is a directive that defines a preprocessor macro. #define __cdecl
defines a macro with identifier __cdecl
and empty replacement. If such macro is defined, the processor will replace all instances of the __cdecl
with an empty string.
So why place a __cdecl before function name as it's just nothing ?
Take a look at the directives at the beginning of the definition in question:
#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) #else
The macro is defined conditionally. When the macro is not defined, __cdecl
will not expand to nothing. When not expanded to nothing, __cdecl
is a microsoft specific function specifier as you have discovered.
The conditionally defined macro allows one to write code that uses __cdecl
on systems that allow it, and automatically remove it on systems that do not.
But I'm still confused with the #if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) line, what does it mean?
It is a preprocessor directive that test whether the macro _MSC_VER
has greater value than 800, or if macro _STDCALL_SUPPORTED
is defined. If the test is false, then the code between #if and #else is removed. If it is true, then the code between #else and #endif is removed.