Extern and extern "C" for variables

I am writing a general C ++ library to use a C program. However, I have a question about externand extern "C".

Consider the following code

My header file is as follows:

#ifdef __cplusplus      
     extern "C" int global;
     extern "C" int addnumbers(int a, int b); 
 #else
      extern int global;
 #endif

This works great; I just need to declare

int global;

in my .cpp or my .c file. However, I do not understand:

What is the difference between extern "C"and externhere? I tried to comment extern "C" int globaland it works! What for?

, extern "C" C-. extern "C" int addnumbers(int,int). , ++-, C, extern "C". , - , ? , C ++ global, extern not extern "C". ? .

: , , , , .

+4
4

extern "C" ++ ( ), "C linkage" - C-. " ", . , - . , mangling.

(MS Visual Studio) C ++ , "" extern "C" ++. :

error LNK2001: unresolved external symbol "int global" (?_global)

++, global dumpbin,

00B 00000014 SECT4  notype       External     | ?global@@3HA (int global)

, MS Visual Studio , C- - C-.


, :

namespace example {
    int global;
}

, C . ++:

namespace example {
    extern "C" int global;
}

:

extern "C", C- - , . , , ( ).

+7

extern , (), , , ​​ , "" .

while extern "C" , , ++, addnumbers_i_i ( - ) , c addnumbers

+2

"++ C: extern" C ". , extern" C ", , C. , - extern" C ", ".

++ , . extern "C" C.

0

I found that extern "C" is used to make a C ++ function compiled in the C standard, and it is not related to variables, since the solutions to the function name in C and C ++ are different. For example, "void foo (int x, int y)", the C compiler will translate it to "_foo", while the C ++ compiler will translate it to "_foo_int_int".

0
source

All Articles