`
shake863
  • 浏览: 639341 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

C和C++中如何互相调用

阅读更多

因为历史上是先有C后有C++,所以C++中调用C中的函数加个extern "C" 既可.
假如C的文件为c.c和c.h,C中有C_fun()函数
C++的文件为cpp.cpp和cpp.h
-----------------------------------------------------------------------------
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()
{
    .....
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics