When browsing through a draft of the standard (N4527), I found the following paragraph ([alg.c.library]):
The function signature:
bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *));
is replaced by the two declarations:
extern "C" void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*)); extern "C++" void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*));
And the same stuff for qsort
.
I also found in [dcl.link]:
If two declarations declare functions with the same name and parameter-type-list (8.3.5) to be members of the same namespace or declare objects with the same name to be members of the same namespace and the declarations give the names different language linkages, the program is ill-formed;
What is the purpose of these two extern
declaration of the same function? Why is this block not ill-formed?
extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit.
Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files.
The parameter type lists are not the same. Really. I'm not kidding. The two compar
arguments have different types: in the first declaration, because the function is extern "C"
, the compar
function is also extern "C"
; in the second one, the compar
function is extern C++"
. And that's why there are two declarations: so that you can call bsearch
with functions with either language linkage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With