Can an extern "C"
function accept or return C++-specific data types, such as references, pointers-to-members, or non-POD classes (by value)? I cannot find anything in the C++ standard that forbids this. Logically, I would expect the standard to say something about it, as the C ABI is not necessarily suitable for passing such types around.
The reason for me wanting to use C linkage has nothing to do with C compilers. The function is called only from C++ code. I just want to export unmangled function names from my dynamic libraries.
A silly code example:
class Foo {
public:
virtual void doit() = 0;
};
class Bar : public Foo {
public:
void doit() { std::cout << "Bar" << std::endl; }
};
extern "C" Foo& getFoo() { static Bar bar; return bar; }
extern "C" Bar getBar() { return Bar(); }
This compiles with GCC on Linux, and works as expected. Should it, standard-wise?
The question is a follow-up to a discussion in the comments to this question.
Update I have tested this with the Comeau compiler, it didn't complain.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…