#ifdef__cplusplus主要实现C与C++的相互调用

来源:岁月联盟 编辑:zhu 时间:2009-02-21
主要实现C与C 的相互调用问题

c.h的实现
#ifndef _c_h_
#define _c_h_
#ifdef __cplusplus
extern /"C/" {
#endif
void C_fun();
#ifdef __cplusplus
}
#endif
#endif
-----------------------------------
c.c的实现
#include /"c.h/"
void C_fun()
{
}
------------------------------------
在擦cpp.cpp中调用c.c中的C_test()
cpp.cpp的实现
#include /"c.h/"
int main()
{
C_fun()
}
其中__cplusplus是C 编译器的保留宏定义.就是说C 编译器认为这个宏已经定义了.
所以关键是extern /"C/" {}
extern /"C/"是告诉C++编译器件括号里的东东是按照C的obj文件格式编译的,要连接的话按照C的命名规则去找.
================================
那么C中是如何调用C 中的函数cpp_fun()呢?
因为现有C后有C , 所以只能从C 的代码中考虑了.
加入C 中的函数或变量有可能被C中的文件掉用,则应该这样写,也是用extern /"C/"{}
不过是代码中要加,头文件也要加,因为可能是C 中也调用
--------------------------------------
cpp.h的实现
#ifndef _c_h_
#define _c_h_
#ifdef __cplusplus
extern /"C/" {
#endif
void CPP_fun();
#ifdef __cplusplus
}
#endif
#endif
.-----------------------------------------------
Cpp.cpp的实现
extern /"C/" { //告诉C 编译器,扩号里按照C的命名规则编译
void CPP_fun()
{
.....
}

图片内容