Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of extern C AND C++ for a single function (bsearch / qsort)? [duplicate]

Tags:

c++

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?

like image 745
Holt Avatar asked Jul 15 '17 20:07

Holt


People also ask

What is the purpose of extern C?

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.

Is extern C necessary?

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.

What is extern C in header file?

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.


1 Answers

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.

like image 142
Pete Becker Avatar answered Oct 05 '22 22:10

Pete Becker