在用C++的项目源码中,经常会不可避免的会看到下面的代码:
#ifdef __cplusplus
extern "C" {
#endif
/*...*/
#ifdef __cplusplus
}
#endif它到底有什么用呢,你知道吗?而且这样的问题经常会出现在面试or笔试中。下面我就从以下几个方面来介绍它:
1、#ifdef _cplusplus/#endif _cplusplus及发散
2、extern “C”
2.1、extern关键字
2.2、”C”
2.3、小结extern “C”
3、C和C++互相调用
3.1、C++的编译和连接
3.2、C的编译和连接
3.3、C++中调用C的代码
3.4、C中调用C++的代码
4、C和C++混合调用特别之处函数指针
1、#ifdef _cplusplus/#endif _cplusplus及发散
在介绍extern “C”之前,我们来看下#ifdef _cplusplus/#endif _cplusplus的作用。很明显#ifdef/#endif、#ifndef/#endif用于条件编译,#ifdef _cplusplus/#endif _cplusplus——表示如果定义了宏_cplusplus,就执行#ifdef/#endif之间的语句,否则就不执行。
在这里为什么需要#ifdef _cplusplus/#endif _cplusplus呢?因为C语言中不支持extern “C”声明,如果你明白