I'm writing a C++ shared library for a C program to use. However, I have a question about extern
and extern "C"
.
Consider the following code
My header file is like this:
#ifdef __cplusplus
extern "C" int global;
extern "C" int addnumbers(int a, int b);
#else
extern int global;
#endif
This works perfectly fine; I just have to declare
int global;
in either my .cpp or my .c file. However, what I don't understand is:
What is the difference between extern "C"
and extern
here? I tried commenting out extern "C" int global
and it works! Why?
I know that extern "C"
is used for making C linkage. That's why I have extern "C" int addnumbers(int,int)
. In other words, if I want to write a C++ function that is to be used in a C program, I write extern "C"
. Now, what about global variables - the situation is different here I guess? I want the C program to use a C++ variable named global
, but I can use extern
not extern "C"
. Why is that? This is not intuitive to me.
Comment: I don't think this is a duplicate, because I'm asking what the difference is when you use it for variables versus functions.
See Question&Answers more detail:os