方法一:在C函数加上 extern 关键字,在相应的c++文件中用 extern “C” {include “c.h”}引入C的头文件
---------/*Max.h*/-------------------------
| #ifndef _MAX_H_ #define _MAX_H_ extern int max(int x, int y); #endif |
| #ifndef _MAX_H_ #define _MAX_H_ extern int max(int x, int y); #endif |
---------//*Max.c*/ ---------
| #include “Max.h” int max(int x, int y) { return x>y?x:y; } |
------------/*Test.cpp*/-------------
| extern "C"{ #include "max.h" } int main(void) { int a=2, b=90; int c = 0; c = max(a,b); } |
方法二:利用C++宏 __cplusplus
----------/*Max.h*/-------------
| #ifndef _MAX_H_ #define _MAX_H_ #ifdef __cplusplus extern "C"{ #endif extern int max(int x, int y); #ifdef __cplusplus } #endif #endif /*_MAX_H_*/ |
--------------/*Max.c*/----------------
| #include “Max.h” int max(int x, int y) { return x>y?x:y; } |
-----------/*Test.cpp*/---------------
| #include "max.h" int main(void) { int a=2, b=90; int c = 0; c = max(a,b); } |
因为C中没有定义__cplusplus宏,所以在C编译器看来,Max.h为:
extern int max(int x, int y);
而在c++看来,Max.h为:
extern "C"{
extern int max(int x, int y);
}
本文介绍两种在C++项目中使用C代码的方法:一是通过在C函数声明前添加extern关键字并在C++文件中使用extern C{}

1563

被折叠的 条评论
为什么被折叠?



