extern C的使用

作用简介extern “C”通知编译器将extern “C”所包含的代码按照C的方式编译和链接。主要目的是 C++代码可以调用C接口

因为C与C++编译后在符号库中的名字不同

C _func

C++ _func_type_type_type


1、在C++的使用示例:

1.1直接混编代码

#ifdef __cplusplus

extern "C" {

#endif 

/* C code */

#ifdef __cplusplus

}

#endif


1.2 调用其他C文件函数

/* chead.h */

extern "C" int add(int a, int b); //c 的头文件中必须这样声明

/* cfunc.c */

#include "chead.h"

int add(int a, int b)

 return (a+b);

}

/* cplus.cpp */

#include <stdio.h>

extern "C" //调用C接口需要使用 extern "C" 声明

{

#include "chead.h"

}

int main()

 printf("a+b=%d\n",add(10,1)); 

 return 0;

}

2、在C中调用C++ 

2.1 调用接口

/* cplushead.h */

extern "C" {

 int add(int a, int b); //c++头文件中需要用 extern "C"声明

}

/* cplusplus.cpp */

#include <stdio.h>

#include "cplushead.h"

int add(int a, int b)

{

 return (a+b);

}

/ * cfile.c */

#include <stdio.h>

extern int add(int a, int b); //必须用exter声明,不可包含c++头文件cplushead.h

int main()

 printf("a+b=%d\n",add(10,1)); 

 return 0;

}


2.2使用C++库,由于C++库已经编译完成,而C++与C的符号表不同,故不能直接调用,可以再次对C++库进行二次封装,提供C接口给C的代码使用,编译自己封装的库时要用g++,且需要指定 -lstdc++表明使用C++标准库,否则出现错误“undefined reference to `__gxx_personality_v0'”

/* clib_head.h */

#ifdef __cpluscplus

extern "C" {

#endif 

 /* new api declare for C */

#ifdef __cpluscplus

}

#endif

/* clib_func.c */

#include "xxxheaders.h"

int api_for_c(int a, intb)

{

 return api_from_cpluspluslib(a,b);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值