The standard C function declaration syntax (WINAPI) [duplicate] - c++

This question already has answers here:
What does "WINAPI" in main function mean?
(4 answers)
Closed 7 years ago.
I know you might think this question already been answered but it is not, or at least it was not very clear to me.
int WINAPI WinMain (){}
This is a pseudo form of the famous winmain function.
My question is about the calling convention WINAPI, in particular its placement between the "return type" and the "function name". Is this Standard C? Because I referenced the Brian W. Kernighan and Dennis M. Ritchie book and I didn't see this form.
I also have searched for its meaning and they said it's a macro to place _stdcall instead. So please don't tell me the question is duplicated.
And here is one of the questions that might be very close to mine
What does "WINAPI" in main function mean?
I want a clear answer for this WINAPI: Is it standard C? So I can place a calling convention after the return type in any function declaration and I then give it to any C compiler in the world? Or is it something will work only on Microsoft compilers? And if so, can anyone impose their rules on the C syntax?
I'm sorry I know my question might be trivial for many of you, but I searched everywhere about the functions declaration syntax and all sources denied this calling convention place.

The essential answer: No. A function declaration, as defined by the C language standard, has no elements between the return type and the function name. So int __bootycall myFunc(int qux) is not standard C (or C++), even though C implementations are allowed to reserve __customIdentifiers for their own exclusive use.
However.
The need for calling-convention specifiers (e.g. __cdecl) is clear; a lot of (especially early non-UNIX [especially MS-DOS]) platforms had more than one calling convention to choose from, and specifying the calling convention of a function was as important as, if not more important than, the parameter list of that function. Hence the need to slot a little something extra in there.
At that time (even before C89), there was no provision made for architecture-specific function attributes (presumably because C, designed for the sole purpose of implementing UNIX utilities, didn't need any). This would later be remedied in C99, and if C99 had existed at that point, it's likely that __cdecl et al. would have been function attributes, not random identifiers shoved in there. But as it was, when the need arose to specify non-default calling conventions, there were four reasonable places to put it: Before the return type, between the return type and the function name, between the function name and the opening parenthesis of the argument list, and after the argument list.
I'm speculating here, but it seems like the second option would have made the most sense. This was pre-C++, remember; there was no post-arglist-const, and the only thing that could show up before the return type was static, which specified linkage rather than anything about the function per se. That left before or after the function name, and separating the function name from its argument list would have reduced readability. That left the slightly unusual position between the return type and the function name as the best of a bad bunch.
The rest is history. Later compilers took advantage of the nascent __attribute__ syntax to put the calling convention keyword in a more appropriate place, but DOS-based compilers (of which Microsoft C was one of the first) shoved it after the return type.

Both the __stdcall and the position of the keyword are Microsoft specific. Any compiler vendor is able to add non-standard syntax to their implementation.
At the very top of this MSDN article:
Microsoft Specific
It also mentions the WINAPI macro at the end of the page:
In the following example, use of __stdcall results in all WINAPI function types being handled as a standard call: [...]`
This form works on both Microsoft C++ Compiler and the MinGW toolchain, which implements GCC for Windows.
But in general GCC uses this other form using it's attributes:
int WinMain() __attribute__((stdcall)) // or WINAPI if using the macro
{}
It's possible however that in the future we have those in a more standard syntax (the stdcall part still being platform specific) by using the recent C++11 generalized attributes such as.
[[ms::stdcall]]
int WinMain() {}
In fact both GCC and Clang already supports the standard generalized attributes as an alternative to the compiler specific attribute syntax.

The answer to your clear question:
WINAPI, Is it a standard C?
is No. __stdcall is a Microsoft extension.

WINAPI is a macro defined in windows.h, which expands to __stdcall. Both windows.h and __stdcall are Windows-specific -- no industry-wide standard defines any aspect of their meaning.
The C and C++ standards do define keywords that have related effects on a function definition: inline, _Noreturn (C2011), and static. All of these keywords are normally placed before the return type, but if I'm reading C2011 correctly, this is not actually required by the syntax: you could perfectly well write
int static foo(void) { return 42; }
These keywords are called function specifiers and storage class specifiers.
Do not confuse them with type specifiers and type qualifiers, which can also appear in this position, but modify the return type when they do.

Related

Why can't C functions be name-mangled?

I had an interview recently and one question asked was what is the use of extern "C" in C++ code. I replied that it is to use C functions in C++ code as C doesn't use name-mangling. I was asked why C doesn't use name-mangling and to be honest I couldn't answer.
I understand that when the C++ compiler compiles functions, it gives a special name to the function mainly because we can have overloaded functions of the same name in C++ which must be resolved at compile time. In C, the name of the function will stay the same, or maybe with an _ before it.
My query is: what's wrong with allowing the C++ compiler to mangle C functions also? I would have assumed that it doesn't matter what names the compiler gives to them. We call functions in the same way in C and C++.
It was sort of answered above, but I'll try to put things into context.
First, C came first. As such, what C does is, sort of, the "default". It does not mangle names because it just doesn't. A function name is a function name. A global is a global, and so on.
Then C++ came along. C++ wanted to be able to use the same linker as C, and to be able to link with code written in C. But C++ could not leave the C "mangling" (or, lack there of) as is. Check out the following example:
int function(int a);
int function();
In C++, these are distinct functions, with distinct bodies. If none of them are mangled, both will be called "function" (or "_function"), and the linker will complain about the redefinition of a symbol. C++ solution was to mangle the argument types into the function name. So, one is called _function_int and the other is called _function_void (not actual mangling scheme) and the collision is avoided.
Now we're left with a problem. If int function(int a) was defined in a C module, and we're merely taking its header (i.e. declaration) in C++ code and using it, the compiler will generate an instruction to the linker to import _function_int. When the function was defined, in the C module, it was not called that. It was called _function. This will cause a linker error.
To avoid that error, during the declaration of the function, we tell the compiler it is a function designed to be linked with, or compiled by, a C compiler:
extern "C" int function(int a);
The C++ compiler now knows to import _function rather than _function_int, and all is well.
It's not that they "can't", they aren't, in general.
If you want to call a function in a C library called foo(int x, const char *y), it's no good letting your C++ compiler mangle that into foo_I_cCP() (or whatever, just made up a mangling scheme on the spot here) just because it can.
That name won't resolve, the function is in C and its name does not depend on its list of argument types. So the C++ compiler has to know this, and mark that function as being C to avoid doing the mangling.
Remember that said C function might be in a library whose source code you don't have, all you have is the pre-compiled binary and the header. So your C++ compiler can't do "it's own thing", it can't change what's in the library after all.
what's wrong with allowing the C++ compiler to mangle C functions also?
They wouldn't be C functions any more.
A function is not just a signature and a definition; how a function works is largely determined by factors like the calling convention. The "Application Binary Interface" specified for use on your platform describes how systems talk to each other. The C++ ABI in use by your system specifies a name mangling scheme, so that programs on that system know how to invoke functions in libraries and so forth. (Read the C++ Itanium ABI for a great example. You'll very quickly see why it's necessary.)
The same applies for the C ABI on your system. Some C ABIs do actually have a name mangling scheme (e.g. Visual Studio), so this is less about "turning off name mangling" and more about switching from the C++ ABI to the C ABI, for certain functions. We mark C functions as being C functions, to which the C ABI (rather than the C++ ABI) is pertinent. The declaration must match the definition (be it in the same project or in some third-party library), otherwise the declaration is pointless. Without that, your system simply won't know how to locate/invoke those functions.
As for why platforms don't define C and C++ ABIs to be the same and get rid of this "problem", that's partially historical — the original C ABIs weren't sufficient for C++, which has namespaces, classes and operator overloading, all of which need to somehow be represented in a symbol's name in a computer-friendly manner — but one might also argue that making C programs now abide by the C++ is unfair on the C community, which would have to put up with a massively more complicated ABI just for the sake of some other people who want interoperability.
MSVC in fact does mangle C names, although in a simple fashion. It sometimes appends #4 or another small number. This relates to calling conventions and the need for stack cleanup.
So the premise is just flawed.
It's very common to have programs which are partially written in C and partially written in some other language (often assembly language, but sometimes Pascal, FORTRAN, or something else). It's also common to have programs contain different components written by different people who may not have the source code for everything.
On most platforms, there is a specification--often called an ABI [Application Binary Interface] which describes what a compiler must do to produce a function with a particular name which accepts arguments of some particular types and returns a value of some particular type. In some cases, an ABI may define more than one "calling convention"; compilers for such systems often provide a means of indicating which calling convention should be used for a particular function. For example, on the Macintosh, most Toolbox routines use the Pascal calling convention, so the prototype for something like "LineTo" would be something like:
/* Note that there are no underscores before the "pascal" keyword because
the Toolbox was written in the early 1980s, before the Standard and its
underscore convention were published */
pascal void LineTo(short x, short y);
If all of the code in a project was compiled using the same compiler, it
wouldn't matter what name the compiler exported for each function, but in
many situations it will be necessary for C code to call functions that were
compiled using other tools and cannot be recompiled with the present compiler
[and may very well not even be in C]. Being able to define the linker name
is thus critical to the use of such functions.
I'll add one other answer, to address some of the tangential discussions that took place.
The C ABI (application binary interface) originally called for passing arguments on the stack in reverse order (i.e. - pushed from right to left), where the caller also frees the stack storage. Modern ABI actually uses registers for passing arguments, but many of the mangling considerations go back to that original stack argument passing.
The original Pascal ABI, in contrast, pushed the arguments from left to right, and the callee had to pop the arguments. The original C ABI is superior to the original Pascal ABI in two important points. The argument push order means that the stack offset of the first argument is always known, allowing functions that have an unknown number of arguments, where the early arguments control how many other arguments there are (ala printf).
The second way in which the C ABI is superior is the behavior in case the caller and callee do not agree on how many arguments there are. In the C case, so long as you don't actually access arguments past the last one, nothing bad happens. In Pascal, the wrong number of arguments is popped from the stack, and the entire stack is corrupted.
The original Windows 3.1 ABI was based on Pascal. As such, it used the Pascal ABI (arguments in left to right order, callee pops). Since any mismatch in argument number might lead to stack corruption, a mangling scheme was formed. Each function name was mangled with a number indicating the size, in bytes, of its arguments. So, on 16 bit machine, the following function (C syntax):
int function(int a)
Was mangled to function#2, because int is two bytes wide. This was done so that if the declaration and definition mismatch, the linker will fail to find the function rather than corrupt the stack at run time. Conversely, if the program links, then you can be sure the correct number of bytes is popped from the stack at the end of the call.
32 bit Windows and onward use the stdcall ABI instead. It is similar to the Pascal ABI, except push order is like in C, from right to left. Like the Pascal ABI, the name mangling mangles the arguments byte size into the function name to avoid stack corruption.
Unlike claims made elsewhere here, the C ABI does not mangle the function names, even on Visual Studio. Conversely, mangling functions decorated with the stdcall ABI specification isn't unique to VS. GCC also supports this ABI, even when compiling for Linux. This is used extensively by Wine, that uses it's own loader to allow run time linking of Linux compiled binaries to Windows compiled DLLs.
C++ compilers use name mangling in order to allow for unique symbol names for overloaded functions whose signature would otherwise be the same. It basically encodes the types of arguments as well, which allows for polymorphism on a function-based level.
C does not require this since it does not allow for the overloading of functions.
Note that name mangling is one (but certainly not the only!) reason that one cannot rely on a 'C++ ABI'.
C++ wants to be able to interop with C code that links against it, or that it links against.
C expects non-name-mangled function names.
If C++ mangled it, it would not find the exported non-mangled functions from C, or C would not find the functions C++ exported. The C linker must get the name it itself expects, because it does not know it is coming from or going to C++.
Mangling the names of C functions and variables would allow their types to be checked at link time. Currently, all (?) C implementations allow you to define a variable in one file and call it as a function in another. Or you can declare a function with a wrong signature (e.g. void fopen(double) and then call it.
I proposed a scheme for the type-safe linkage of C variables and functions through the use of mangling back in 1991. The scheme was never adopted, because, as other have noted here, this would destroy backward compatibility.

Why is no argument in a function prototype preferred?

I have a question about coding style in C++.
I prefer to use void explicitly in function prototypes.
However, during reading an article about void type in Wikipedia, I have seen that giving no argument in a function prototype is preferred.
Why is no argument in the prototype preferred?
I am so curious if there is a specific reason.
C++ had function prototypes before C did, and C++ has 'always' required prototypes in effect. Therefore, there was no problem or ambiguity about empty brackets (parentheses) meaning no arguments.
By contrast, C did not acquire function prototypes until long after C++ had them, and it had a legacy base to deal with. Until function prototypes were introduced, C functions with non-integer return types had to be declared as:
double sin();
char *malloc(); /* There wasn't void * -- or C++ style // comments */
struct whatnot *new_whatnot();
The C standardization committee could not afford to break all the existing C code; the standard would have failed. So, the C standardizers adopted sometype function(void) to indicate explicitly 'no arguments'. To this day, sometype function() means 'a function returning a sometype value taking an undefined (but not variable) number of arguments of undefined type'.
Because C++ had the empty brackets (empty parentheses) notation, there was no need for the (void) notation, but it was added to C++ to match the C standard and make it easier to migrate code between standard C and C++.
Code written natively for C++ should use the native, empty brackets notation.
Code written natively for C must use the explicit (void) notation because the empty parentheses means something quite different (and relatively undesirable).
Code written to be migratable between C and C++ might use the explicit (void) notation to ensure that both compilers see the same specification.
What is prefered and what is a good practice are quite different. I believe that is just a choice of the programmer.

Is the C++ calling convention constrained by the standard, since the return type of a function does not need to be defined when the fn is declared?

While studying the One Definition Rule in Wikipedia, I became stuck on the following example in the Examples section:
struct S; // declaration of S
...
S f(); // ok, no definition required
...
I know that space on the stack needs to be allotted for the return value, but seeing this example made me think that C++ calling conventions might dictate that stack management for the return value is handled by the code block in which the function is defined, rather than the code block in which it is called. So I investigated "C vs. C++ calling convention" (recalling that the issue of stack return value allocation might be a primary difference), and came across this answer, which indicates that "calling convention" is not defined by the standard.
However, given the apparent requirement that the above code snippet is valid, it seems to me that there must be some constraints on calling convention in order to support the above code snippet.
Am I right? Does the C++ standard implicitly require that stack management for the return value of a function be handled by the code that defines the function, in order to support the syntax above?
As mentioned in the comments
As you have written your example, Both Struct S and function f are forward declarations. The Compiler Will indeed complain if you attempt to use either
** EDIT as noted by Steven Sudit, function f is not a forward declaration but a function prototype**
and
Also, I believe that default calling convention ( and optional calling conventions ) are explicitly implementation dependent with the exception of those with external linkage. If you search the c++ standard for "calling convention". It is mentioned only once in section 7.5 Linkage Specifications
As to your specific question
Am I right? Does the C++ standard implicitly require that stack management for the return value of a function be handled by the code that defines the function, in order to support the syntax above?
Definitely not, as many compilers support calling conventions where the values are not even passed/returned on the stack (FASTCALL) or microsofts version of (thiscall) where the caller cleans the stack.
The C/C++ standard does not define calling conventions. That is the job of compiler vendors to implement on their own, as evident by the fact that calling convention keywords start with underscores indicating they are vendor-provided extensions.
The C/C++ standard defines the base rules (how to assign values to parameters and return values, pass by-value vs by-reference, etc), but the calling conventions dictate how to accomplish those rules in different ways (passing parameters via stack or registers, in which order, which registers, who cleans up the stack, etc).
In the casev of x86, vendors have agreed on the semantics of the __cdecl and __stdcall calling conventions for interoperability (although there are some slight variations in __cdecl implementations in some cases), but other calling conventions are vendor-specific (Microsoft's __fastcall/__thiscall, Borland's __fastcall/__safecall/__msfastcall, etc).
In the case of x64, there is only one calling convention, dictated by x64 itself. Calling convention keywords are silently ignored by x64 compiler so existing code will still compile and work correctly (as long as it is not using inline assembly to access/manipulate the call stack directly).

Compiler independent C++ properties

Microsoft Visual C++ compiler has the property declaration construction
__declspec( property( get=get_func_name, put=put_func_name ) )
Is there a compiler independent version of Microsoft C++ __declspec(property(...)) or another analogs?
No.
As usual, an identifier preceded by __ is reserved to the compiler. In C++03 you have __cpluscplus (to identify C++ vs C), __FILE__ and __LINE__. All those are preprocessor entities.
In C++0x, the difference is blurred by the introduction of the __attribute__ word which is the first I know of that has semantics value, but it still does not do what you're looking for.
EDIT: Addressing #James spot on comment.
As Nicola Musatti says, there was a Borland proposal, primarily because Borland Delphi uses Properties heavily, and C++Builder (their C++ 'equivalent' to Delphi) therefore requires it.
In C++Builder, the code looks a bit like this.
__property __int64 Size = {read=GetSize, write=SetSize};
No. Similar mechanisms were proposed to the C++ standard committee but none was ever accepted (Here is one such proposal from Borland).
I've seen template based toy implementations, but they tend to be too inconvenient to be of practical use, the major problems being:
As nested class instances are not members of the enclosing class (as are Java inner class instances), you have to explicitly "connect" a property to its enclosing class, which makes declaration and initialization cumbersome.
There is no way to call function-like entities without parentheses, so you cannot invoke a custom-made property as if you were accessing a variable.

calling qsort with a pointer to a c++ function

I have found a book that states that if you want to use a function from the C standard library which takes a function pointer as an argument (for example qsort), the function of which you want to pass the function pointer needs to be a C function and therefore declared as extern "C".
e.g.
extern "C" {
int foo(void const* a, void const* b) {...}
}
...
qsort(some_array, some_num, some_size, &foo);
I would not be surprised if this is just wrong information, however - I'm not sure, so: is this correct?
A lot depends on whether you're interested in a practical answer for the compiler you're using right now, or whether you care about a theoretical answer that covers all possible conforming implementations of C++. In theory it's necessary. In reality, you can usually get by without it.
The real question is whether your compiler uses a different calling convention for calling a global C++ function than when calling a C function. Most compilers use the same calling convention either way, so the call will work without the extern "C" declaration.
The standard doesn't guarantee that though, so in theory there could be a compiler that used different calling conventions for the two. At least offhand, I don't know of a compiler like that, but given the number of compilers around, it wouldn't surprise me terribly if there was one that I don't know about.
OTOH, it does raise another question: if you're using C++, why are you using qsort at all? In C++, std::sort is almost always preferable -- easier to use and usually faster as well.
This is incorrect information.
extern C is needed when you need to link a C++ library into a C binary; it allows the C linker to find the function names. This is not an issue with function pointers (as the function is not referenced by name in the C code).