extern “C“

在很多程序中,都会见到如下代码段:

#ifdef __cplusplus
extern "C" {
#endif

/*
 * C代码段
 */

#ifdef __cplusplus
}
#endif

__cplusplus是C++中定义的宏,表示这是一段C++代码,编译器按照C++的方式进行编译。如果这时我们需要使用C语言的代码,那么就需要加上extern "C" { 代码段 }说明一下该部分为C代码段,编译器用C语言的模式编译,否则编译器会把C代码按照C++模式编译,会报错。

主要是因为C++支持函数重载,而C不支持,两者的编译规则也不一样。函数被C++编译后在符号库中的名字和C语言不同。例如,假设某个函数原型为:void foo(int x, int y);该函数被C编译器编译后在符号库中的名字可能为_foo,而C++编译器则会产生像_foo_int_int之类的名字(不同编译器生成的名字可能不同,但是都采用了相同的机制)。_foo_int_int这样的名字包含了函数名、参数数量以及参数类型信息,C++就是靠这种机制来实现函数重载的。

1、在C++代码中调用C函数(***常用)

test.h

#ifndef _TEST_H_
#define _TEST_H_
#ifdef __cplusplus
extern "C" {
#endif

int add(int x, int y);

#ifdef __cplusplus
}
#endif
#endif

test.c

#include "test.h"

int add(int x, int y)
{
    return x + y;
}

main.cpp

#include <iostream>
#include "test.h"
using namespace std;
using std::cout;
using std::endl;

int main(int argc, char *argv[])
{
    int a = 2;
    int b = 8;
    cout << "sum = " << add(a, b) << endl;

    return 0;
}

结论:在C++代码中调用C函数时,则需在相应的C(.h)头文件中加上extern "C" {}

2、在C代码中调用C++函数

test.h

#ifndef _TEST_H_
#define _TEST_H_
#ifdef __cplusplus
extern "C" {
#endif
int add(int x, int y);

#ifdef __cplusplus
}
#endif
#endif

test.cpp

#ifdef __cplusplus
extern "C" {
#endif

#include "test.h"

int add(int x, int y)
{
    return x + y;
}

#ifdef __cplusplus
}
#endif

main.c

#include <stdio.h>
#include "test.h"

int main(int argc, char *argv[])
{
    int a = 2;
    int b = 8;
    printf("sum = %d\n", add(a, b));
}

结论:在C代码中调用C++函数时,则需在相应的C++(.h)头文件和源文件(.cpp)中都加上extern "C" {}

参考链接:

#ifdef __cplusplus extern"C" { #endif 的解释 - NYC's Blog

“#ifdef __cplusplus extern "C" { #endif”的定义 - 奔跑的兔子 - 博客园

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值