Thomas Eding
Thomas Eding

Reputation: 1

extern "C" function accessing code

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"?

Upvotes: 0

Views: 2520

Answers (4)

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

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.

Upvotes: 1

asaelr
asaelr

Reputation: 5456

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.

Upvotes: 1

jdehaan
jdehaan

Reputation: 19938

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.

Upvotes: -2

CB Bailey
CB Bailey

Reputation: 793199

No. There is no restriction on extern "C" functions accessing functions and variables with C++ language linkage.

C++ extern "C" functions are often used to provide a C interface into code with C++ language linkage so it would be more than a little restrictive if this were the case.

Upvotes: 6

Related Questions