C++调用C代码
一个C语言文件p.c
复制代码
1
2
3
4
5#include <stdio.h> void print(int a,int b) { printf("这里调用的是C语言的函数:%d,%dn",a,b); }
一个头文件p.h
复制代码
1
2
3
4
5
6#ifndef _P_H #define _P_H void print(int a,int b); #endif
C++文件调用C函数
复制代码
1
2
3
4
5
6
7
8
9#include <iostream> using namespace std; #include "p.h" int main() { cout<<"现在调用C语言函数n"; print(3,4); return 0; }
执行命令
复制代码
1
2gcc -c p.c g++ -o main main.cpp p.o
编译后链接出错:main.cpp对print(int, int)未定义的引用。
原因分析
- p.c我们使用的是C语言的编译器gcc进行编译的,其中的函数print 编译之后,在符号表中的名字为 _print
- 我们链接的时候采用的是g++进行链接,也就是C++链接方式,程序在运行到调用 print函数的代码时,会在符号表中寻找_print_int_int(是按照C ++的链接方法来寻找的,所以是找_print_int_int而不是找_print )的名字,发现找不到,所以会t提示“未定义的引用”
- 此时如果我们在对print的声明中加入 extern “C” ,这个时候,g ++编译器就会按照C语言的链接方式进行寻找,也就是在符号表中寻找_print ,这个时候是可以找到的,是不会报错的。
总结
编译后底层解析的符号不同,C语言是_print,C++是_print_int_int
解决调用失败问题
修改p.h文件
复制代码
1
2
3
4
5
6#ifndef _P_H #define _P_H extern "C"{ void print(int a,int b); } #endif
修改后再次执行命令
复制代码
1
2
3gcc -c p.c g++ -o main main.cpp p.o ./main
运行无报错
思考:那C代码能够被C程序调用吗
实验:定义main,c函数如下
复制代码
1
2
3
4
5
6
7
8#include <stdio.h> #include "p.h" int main() { printf("现在调用C语言函数n"); print(3,4); return 0; }
重新执行命令如下
复制代码
1
2gcc -c p.c gcc -o mian main.c p.o
报错:C语言里面没有extern “C“这种写法
C代码既能被C++调用又能被C调用
为了使得p.c代码既能被C++调用又能被C调用
将p.h修改如下
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18#ifndef _P_H #define _P_H #ifdef __cplusplus #if __cplusplus extern "C"{ #endif #endif /* __cplusplus */ void print(int a,int b); #ifdef __cplusplus #if __cplusplus } #endif #endif /* __cplusplus */ #endif /* __P_H */
再次执行命令
复制代码
1
2
3gcc -c p.c gcc -o mian main.c p.o ./mian
结果示意:
到此这篇关于C++调用C接口的实现示例的文章就介绍到这了,更多相关C++调用C接口内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!
最后
以上就是虚幻芹菜最近收集整理的关于C++调用C接口的实现示例的全部内容,更多相关C++调用C接口内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复