我有这个来自 C++ 入门第 5 版:外部链接:
如果一组重载函数中的一个函数是 C 函数,则其他函数必须都是 C++ 函数:
class SmallInt { /* . . . */ }; class BigNum { /* . . . */ }; // the C function can be called from C and C++ programs // the C++ functions overload that function and are callable from C++ extern "C" double calc(double); extern SmallInt calc(const SmallInt&); extern BigNum calc(const BigNum&);
calc
可以从 C 程序和 C++ 程序调用C 版本。附加函数是带有类参数的 C++ 函数,只能从 C++ 程序中调用。声明的顺序并不重要。
所以我从这些声明中了解到我可以将它们放在标题中。例如:
// calc.h #ifdef __cplusplus class SmallInt { /* . . . */ }; class BigNum { /* . . . */ }; // C++ functions can be overloaded extern SmallInt calc(const SmallInt&); extern BigNum calc(const BigNum&); extern "C" #endif double calc(double); // C function
那么我需要在 C 源文件中定义 C 版本,在 C++ 源文件中定义 C++ 版本吗?
// calc.c #include "calc.h" double calc(double){} // do_something // calc.cxx #include "calc.h" SmallInt calc(const SmallInt&){} // do_something BigNum calc(const BigNum&){} // do_something
现在我需要这样编译:
gcc print.c -c && g++ main.cxx print.cxx print.o -o prog
它工作得很好,但我的猜测和实现这段代码是否正确?
只要
extern
C++ 版本 (calc(const SmallInt&)
和) 不能用 C 编译器编译,它们有什么意义?calc(const BigNum&)
太感谢了!