作用简介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);
}