C和C++相互调用

1 C++和C相互调用

  • 实际工程中C++和C代码相互调用是不可避免的。
  • C++编译器能够兼容C语言的编译方式。
  • C++编译器会优先使用C++编译的方式。
  • extern关键字能够强制让C++编译器进行C方式的编译。
extern “C”
{
    // do C-style compilation here
}

编程实验:C++调用C函数

// add.c
#include "add.h"



int add(int a, int b)

{

    return a + b;

}
// add.h
int add(int a, int b);
// main.cpp

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


int main()
{
    int c = add(1, 2);

    printf("c = %d\n", c);

    return 0;
}

采用如下编译方式:

gcc add.c -c -o add.o (OK)

g++ main.cpp add.o (error) : /tmp/ccbiexce.o: In function main:
9main.cpp:(.text+0x19): undefined reference to add(int, int)
collect2: error: ld returned 1 exit status

将main.cpp更改成如下形式即可顺序编译通过:

// main.cpp

#include <stdio.h>

extern "C"
{
#include "add.h"
}

int main()
{
    int c = add(1, 2);

    printf("c = %d\n", c);

    return 0;
}

2 如何保证一段C代码只会以C的方式被编译?

解决方案:

  • __cplusplus是C++编译器内置的标准宏定义;
  • __cplusplus的意义:确保C代码以统一的C方式被编译成目标文件。
#ifdef __cplusplus
extern "C" {
#endif

    //C-style Compilation

#ifdef __cplusplus
}
#endif
// 将main.cpp更改为如下形式即可
#include <stdio.h>


#ifdef __cplusplus
extern "C" {
#endif

#include "add.h"

#ifdef __cplusplus
}
#endif


int main()
{
    int c = add(1, 2);

    printf("c = %d\n", c);

    return 0;
}

编程实验:C调用C++ 函数

解决方法:将C++代码用C编译器进行编译即可。

注意事项

  • C++编译器不能以C的方式编译重载函数。
  • 编译方式决定函数名被编译后的目标名:
    • C++编译方式将函数名和参数列表编译成目标文件;
    • C编译方式只将函数名作为目标名进行编译。

小结

  • extern关键字能够实现C 和C++的相互调用。
  • 编译方式决定符号表中的函数名的最终目标名。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值