What does __stdcall and __cdecl do?

I'm learning how to make dll and lib files using c++ and I see lots of codes that looks like this,

void __stdcall Foo();

void __cdecl Ham();


What do they do and why would you use it?

Also, correct me if I'm wrong.

1. extern "c" tells compiler that don't make my functions symbolized. Am I right?

2. #ifdef __cplusplus tells compiler that only C++ compiler can use this. Am I correct?
__stdcall and __cdecl are "calling conventions"

When you call a function, what happens at the assembly level is all the passed-in parameters are pushed to the stack, then the program jumps to a different area of code. The new area of code looks at the stack and expects the parameters to be placed there.

Different calling conventions push parameters in different ways. Some might push the first parameter first, or some might push the first param last. Or some might keep a parameter in a register and not push it at all.

By specifying a calling convention, you are telling the compiler how the parameters are to be pushed.

Usually you don't have to care about this crap, since it doesn't really matter what convention you use -- they all pretty much do the same thing. But when dealing with external libraries --- it's important for the calling convention used in the lib to match the calling convention used in the code that is calling into the lib, or else your parameters will be all messed up when you call a lib function.

1. extern "c" tells compiler that don't make my functions symbolized. Am I right?


Sort of.

In C++ it tells the compiler not to do any name mangling. Name mangling is necessary to facilitate things like function overloading, but complicates calls across libraries since the mangled name your compiler generates likely won't match the mangled name the lib's compiler generated.

So by saying "don't mangle", you're ensuring the names match.


In C, it doesn't matter because names are never mangled (C doesn't need to do it because it can't overload functions)


2. #ifdef __cplusplus tells compiler that only C++ compiler can use this. Am I correct?


Yes

The __cplusplus identifier will only be defined when compiling code as C++ (or unless you do something stupid like #define it manually)

When compiling as C, it will not be defined.

So anything after #ifdef __cplusplus will be skipped over when compiling as C
Topic archived. No new replies allowed.