Say I have the following C++ code:
int x;
some_class y;
extern "C" {
void foo () {
// do something with x
// do something with y
}
}
Do x and/or y need to be declared with extern "C"?
well, variables aren't needed to be declared using extern "c".
in fact, even functions aren't needed to use extern "C" just because you call them from a function with extern "C"
you can freely write code like:
void bla() {cout<<"bla\n";}
extern "C" void sh() {bla();}
the function "sh" will compile using c++ compiler, so it can freely call bla. extern "C" affect only the name of the function.
C++ methods/functions support overloading which make them link in a slightly more complicated way. What extern "C" does is really to say "don't let me overload and use the good old C way" which makes it compatible with C code.
Edit: Charles Bailey points out that I apparently was wrong about variables linking in an identical way. In other words, if the variables are used by external C code (which they could be since they're not static), you should put them inside extern "C". If you're only using them internally in the file or from external C++ code only, you're fine with keeping them where they are.
extern "C" if need.extern "C" is only useful for functions, not for data. It defines the way the function gets decorated or mangled. The decoration also depends on the calling convention used. Classes cannot be used from C, neither do functions that have classes as a parameter, even if inside an extern "C" block.
The extern "C" make sense where a C library is intended to be used by C and C++ code.
In conclusion having a class within an extern "C" does not make sense, x is just a basic type, having is inside or outside does not matter. The normal way to use the feature would be to have all the content of a header inside such a block. Having an int declaration in a header is not a good idea! That will create a variable for each translation unit and cause trouble at link time... Not sure what you intend to do with code similar to what you posted.
extern "C" is only useful for functions, not for data." That's not true -- e.g. I'd wager that your compiler's standard library implementation has errno declared with C-linkage.extern "C" useful for variables? Both function and variables with external linkage have language linkage.int declaration in a header is not a good idea! That will create a variable for each translation unit and cause trouble at link time..." No, it's declared extern, so must still be defined in exactly one translation unit. Having an int definition in a header file would be a bad idea...extern "C" int x;). Having a declaration of such an object that is a definition (e.g. extern "C" { int x; }) is an error if that header file is included in more than one translation unit.
extern(without the"C").