The difference between external "C" and external

Does it make a difference if I use the specifier extern "C"

for the entire title, or if I use it extern

for each function?

As far as I know, there are none, since only functions and variables can be linked externally, so when I use the specifier extern

in front of each function prototype and external variable, I don't need to use the global extern "C"

declaration !?

Example A:

#ifdef __cplusplus
extern "C" {
#endif

void whatever(void);

#endif

      

Example B:

extern void whatever(void);

      

+3


source to share


2 answers


extern "C"

means that you are using a C library function calling from C ++ code.

Who cares?

A long time ago, the C compiler generated code and address function by name. Therefore, it ignores the parameters.



When overloaded functions were introduced in C ++, it needed a way to specify the same name for different functions. For example, void f()

and void f(int)

are different functions in C ++.

For this, the C ++ compiler does the so-called mangling. It adds some information to the function name that is associated with the function parameters.

extern "C"

means to tell the compiler to "refer to the older style naming convention - no change"

+6


source


There is a difference between the two.

The first says that "the functions here must be compiled to be called from C". C ++ allows multiple functions to have the same name if they accept different arguments. C is not. For this, C ++ includes the argument type information in the compiled name of its functions. As a result, the C compiler cannot find functions. If you add extern "C"

, you get C behavior instead, but you get the ability to call those functions from C.



The latter says that "this function exists in a different compilation unit". This means that the compiler must trust that a function with that signature exists, but not worry that it cannot be seen. It will be when you contact, promise. Declarations (as opposed to definitions) are external by default, since at least C99.

+5


source







All Articles