C and C++ sources should be compiled separatelly, but we can link them together. Because of the different strategy to generate external names in C and C++, we use extern "C".
// this is a c source, compile with gcc
struct Y
{
int y_;
};
int cfunc( double x, struct Y y, double z)
{
return y.y_;
}
///////////////////////////////////////////
// this is a cpp source, compile with g++
#include <iostream>
using namespace std;
struct Y
{
int y_;
virtual void f() {}; // this makes the problem!
};
extern "C" int cfunc( double x, struct Y y, double z);
int main()
{
Y y;
y.y_ = 1;
cout << cfunc(3.14, y, 4.14) << endl; // bad!
return 0;
}
We can use - and frequently we should use - C and C++ programs together.
// C++ header for C files:
extern "C"
{
int f(int);
double g(double, int);
// ...
}
// C++ header for C/C++ files:
#ifdef __cplusplus
extern "C"
{
#endif
int f(int);
double g(double, int);
// ...
#ifdef __cplusplus
}
#endif