C++如何调用已经写好的C接口

2022-07-21,,

目录
  • 1、c++调用c文件
  • 4、思考:那c语言能够调用c接口
  • 5、c接口既能被c++调用又能被c调用

前言:

如何在c++代码中调用写好的c接口?你可能会奇怪,c++不是兼容c吗?直接调用不就可以了,那么我们来测试一下,先看看c++如何调用c代码接口的。

1、c++调用c文件

一个c语言文件test.c

#include <stdio.h> 
void print(int a,int b) 
{ 
    printf("这里调用的是c语言的函数:%d,%d\n",a,b); 
} 


一个头文件test.h

#ifndef _test_h 
#define _test_h 
 
void print(int a,int b); 
 
#endif 


c++文件调用c函数

#include <iostream> 
using namespace std; 
#include "test.h" 
int main() 
{ 
   cout<<"现在调用c语言函数\n"; 
   print(3,4); 
   return 0; 
} 

执行命令

gcc -c test.c 
g++ -o main main.cpp test.o 

编译后链接出错:main.cppprint(int, int)未定义的引用。

那么g++编译器为什么找不到print(int,int)呢,其实在我们学c++重载的时候就提到过c++底层的编译原理。

2、原因分析

test.c我们使用的是c语言的编译器gcc进行编译的,其中的函数print编译之后,在符号表中的名字为 print,通过nm查看.o文件.

$ gcc -c test.c 
$ nm test.o  
                 u _global_offset_table_ 
0000000000000000 t print 
                 u printf 


我们链接的时候采用的是 g++ 进行链接,也就是 c++ 链接方式,程序在运行到调用 print 函数的代码时,会在符号表中寻找 _z5printii(是按照c++的链接方法来寻找的,所以是找 _z5printii 而不是找 print)的名字,发现找不到,所以会提示“未定义的引用”

$ g++ -c test.c 
$ ls 
main.cpp  makefile  test.c  test.h  test.o 
$ nm test.o 
                 u _global_offset_table_ 
                 u printf 
0000000000000000 t _z5printii 


此时如果我们在对print的声明中加入 extern “c” ,这个时候,g++编译器就会按照c语言的链接方式进行寻找,也就是在符号表中寻找print(这才是c++兼容c),这个时候是可以找到的,是不会报错的。

总结:

编译后底层解析的符号不同,c语言是 _printc++ __z5printii

3、解决调用失败问题

修改test.h文件

#ifndef _test_h 
#define _test_h 
extern "c"{ 
void print(int a,int b); 
} 
#endif 


修改后再次执行命令

gcc -c test.c 
g++ -o main main.cpp test.o 
./main 


运行无报错

4、思考:那c语言能够调用c接口吗

实验:定义main.c函数如下

#include <stdio.h> 
#include "test.h" 
int main() 
{ 
    printf("现在调用c语言函数\n"); 
    print(3,4); 
    return 0; 
} 

重新执行命令如下

gcc -c test.c 
gcc -o mian main.c test.o 


报错:c语言里面没有extern “c“这种写法

5、c接口既能被c++调用又能被c调用

为了使得test.c代码既能被c++调用又能被c调用

将test.h修改如下

#ifndef __test_h__ 
#define __test_h__ 
 
#ifdef __cplusplus 
#if __cplusplus 
extern "c"{ 
#endif 
#endif /* __cplusplus */ 
 
extern void print(int a,int b); 
 
#ifdef __cplusplus 
#if __cplusplus 
} 
#endif 
#endif /* __cplusplus */ 
#endif /* __test_h__ */ 


ps:下期介绍一个source insight的插件,快速生成上面的代码

再次执行命令

gcc -c test.c 
gcc -o main main.c test.o 
./main 


结果示意:

到此这篇关于c++如何调用已经写好的c接口的文章就介绍到这了,更多相关c++如何调用c接口内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《C++如何调用已经写好的C接口.doc》

下载本文的Word格式文档,以方便收藏与打印。