extern C can not be used at class level?

George2 picture George2 · Jun 22, 2009 · Viewed 29.2k times · Source

Just want to confirm in Windows environment, VSTS 2008 + C++ project, we could only apply extern C to function level, not be able to apply to class level (so that all member functions from the class use C language name mangling)? I have tried several ways, but always compile error.

thanks in advance, George

Answer

Pavel Minaev picture Pavel Minaev · Dec 23, 2009

You can sort of apply extern "C" to a member function via a very convoluted (but entirely legal) hack:

extern "C" typedef int bar_t(int x);

struct foo {
     bar_t bar; // yes, this declares a nonstatic member function!
};

int foo::bar(int x) { return x; } // definition

This is possible according to ISO C++03 9.3[class.mfct]/9:

a member function can be declared (but not defined) using a typedef for a function type. The resulting member function has exactly the same type as it would have if the function declarator were provided explicitly, see 8.3.5.

However, this doesn't really buy you anything, because of ISO C++03 7.5[dcl.link]/4:

A C language linkage is ignored for the names of class members and the member function type of class member functions.