首页 技术 正文
技术 2022年11月15日
0 收藏 543 点赞 4,550 浏览 1149 个字

因为 C 编译器编译函数时不带参数的类型信息,只包含函数的符号名字。如 void foo( int x ) , C 编译器会将此函数编译成类似 _foo 的符号,C 链接器只要找到了调用函数的符号,就会认为链接成功。而 C++ 编译器为了实现函数重载,会在编译时带上函数的参数信息。如它可以把上面的函数编译成类似于 _foo_int 这样的符号。

所以在 C++ 与 C 相互调用时,要用 extern "C" 加以声明。

下面用两个示例实现它们之间的相互调用(没有优化代码,只是起示例作用)。

C++ 调用 C 函数

/* cfile.c */#include <stdio.h>void C_Func()
{
puts("Hello, I'm C_Func");
}
/* cppfile.cpp */#include <iostream>extern "C" void C_Func(void);int main()
{
C_Func();system("pause");
return 0;
}

C 调用 C++ 内类的成员函数

/* cppfile.cpp */#include <iostream>
#include "cpphfile.h"using namespace std;void Myclass::print()
{
cout << "Hello, I'm print function." << endl;
}
/* cpphfile.h */#ifndef _CPPCLASS_H__
#define _CPPCLASS_H__class Myclass{
public:
void print();
};#endif
/* wrapper.cpp 这个文件实现调用 C++ 的接口*/#include "cpphfile.h"extern "C" {struct wrapper_class{
Myclass w_class;
};struct wrapper_class* get_object()
{
return new struct wrapper_class;
}void call_cpp_print(struct wrapper_class* p)
{
p->w_class.print();
}}
/* cfile.c */#include <stdio.h>struct wrapper_class *test;int main()
{
/* 创建对象 */
test = get_object();/* 调用 C++ 函数 */
call_cpp_print(test);system("pause");
}

小总结

extern "C" 应该只能在 CPP 文件或被引入到 CPP 中的头文件内声明。

通常应该这样使用 extern "C":

#ifdef __cplusplus
extern "C" {
#endif/* your text */#ifdef __cplusplus
}
#endif

C++ 编译器中已经定义了 __cplusplus 这个宏。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,117
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,589
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,435
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,206
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,842
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,927