C++中的 extern “C“

在 C++中,extern "C"是一个链接指示符,用于告诉 C++编译器以 C 语言的方式进行链接。

一、作用

  1. 混合编程:当 C++程序需要调用 C 语言编写的函数或库时,使用extern "C"可以确保 C++编译器正确地识别和链接这些 C 函数。因为 C 和 C++的函数命名规则和调用约定可能不同,extern "C"可以解决这种不兼容性。
  2. 兼容性:对于一些遗留的 C 代码库,或者需要与其他使用 C 语言编写的软件进行交互时,extern "C"可以提供更好的兼容性。

二、使用示例

  1. 调用 C 函数:

假设存在一个 C 语言函数myCFunc,定义如下:

// myCFunc.c
int myCFunc(int a, int b) {
    return a + b;
}

在 C++程序中调用这个函数:

#ifdef __cplusplus
extern "C" {
#endif

int myCFunc(int a, int b);

#ifdef __cplusplus
}
#endif

int main() {
    int result = myCFunc(3, 4);
    std::cout << "Result: " << result << std::endl;
    return 0;
}
  1. 链接 C 语言库:

如果有一个 C 语言库,例如mylib.hmylib.c,可以在 C++程序中使用extern "C"来链接这个库。

首先,编译 C 语言库:

gcc -c mylib.c -o mylib.o
ar rcs libmylib.a mylib.o

然后,在 C++程序中使用:

#ifdef __cplusplus
extern "C" {
#endif

#include "mylib.h"

#ifdef __cplusplus
}
#endif

int main() {
    // 使用 C 语言库中的函数
    int result = myFuncFromLibrary();
    std::cout << "Result from library: " << result << std::endl;
    return 0;
}

需要注意的是,extern "C"只影响链接阶段,它并不会改变 C++代码的语法或语义。在使用extern "C"时,要确保 C 函数的声明和定义与 C++程序中的调用方式一致。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凡人叶枫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值