C和C++中如何互相调用(#ifdef __cplusplus)
来源:互联网 发布:linux 司机售票员问题 编辑:程序博客网 时间:2024/04/30 17:38
本文引用自:http://colding.bokee.com/6416780.html
c.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()
{
.....
}
这个更简单易懂:
c++中调用c函数
因为C++和C是两种完全不同的编译链接处理方式,所以如果直接在C++里面调用C函数,这样链接起来是通不过的,会报链接错误,找不到函数体,所 以要在C++文件里面显示声明以下一些函数是C写的,要用C的方式来处理,这个在C++设计初期就考虑到兼容性的问题,所以是可以解决的。
比如用C写了A.h和A.c这两个文件,里面包括了void A_app(int)这样的函数,那么在需要调用这个函数的CPP文件里面,就需要显示声明一下了。
1.引用头文件前需要加上 extern “C”,如果引用多个,那么就如下所示
extern “C”
{
#include “A.h”
#include “B.h”
#include “C.h”
#include “D.h”
};
然后在调用这些函数之前,需要将函数也全部声明一遍。
2.C++调用C函数的方法,将用到的函数全部重新声明一遍
extern “C”
{
extern void A_app(int);
extern void B_app(int);
extern void C_app(int);
extern void D_app(int);
};
0 0
- C和C++中如何互相调用(#ifdef __cplusplus)
- C和C++中如何互相调用(#ifdef __cplusplus)
- “#ifdef __cplusplus extern "C" { #endif”的定义-----C和C++的互相调用
- extern “C"和#ifdef __cplusplus
- #ifdef __cplusplus extern "C" {
- #ifdef __cplusplus extern "C"
- #ifdef __cplusplus extern "C"
- #ifdef __cplusplus extern "C"
- #ifdef __cplusplus extern "C"
- #ifdef __cplusplus extern "C"
- #ifdef __cplusplus extern “C”
- 关于“#ifdef __cplusplus” 和 " extern "C" "
- 关于"#ifdef __cplusplus" 和 " extern "C" "
- 关于“#ifdef __cplusplus” 和 " extern "C" " (zhuan)
- 关于“#ifdef __cplusplus” 和 " extern "C" "
- extern "C" 和 #ifdef __cplusplus 解释
- C和C++中如何互相调用
- #ifdef __cplusplus extern "C" { #endif /* __cplusplus */
- 静态链接库和动态链接库
- 【Git管理】Git 远程操作
- apache.commons.lang.StringUtils&ArrayUtils
- WoSign数字证书产品有何特别优势? ---- UTN-WoSign根证书系统
- PAT 1078. Hashing (25)
- C和C++中如何互相调用(#ifdef __cplusplus)
- 原始图像数据
- 太阳无限哈哦一
- Terrascan去除地面点
- .net using的用途
- nyoj844 A+B Problem(V)
- SQL表结构复制及表数据复制
- 常见查看LINUX配置命令
- ASD啊实打实的热问题予以分割成不成v