c++和c中的函数相互调用

c++和c文件中的函数的互调的方法都是使用extern "C".

1. c++文件中的函数调用c文件中的函数。

例子如下:假设test.cpp文件中需要调用a.c文件中的fun函数。

//a.h
#ifndef A_H
#define A_H
extern int fun(int a, int b);
#endif

//a.c
#include "a.h"
#include <stdio.h>
int fun(int a, int b)
{
   return a+b;
}
//test.h
#ifndef TEST_H
#define TEST_H
extern "C"{
  #include "a.h"
}
#endif
//test.cpp
#include <iostream>
#include "test.h"
using namespace std;

int main(int argc, char **argv){
    int sum = fun(2,3);
    cout<<sum<<endl;
    return 0;
}


编译方式: gcc -c a.h a.c 会生产a.o文件。

g++ -o test test.h test.cpp a.o会生成test可执行文件。./test运行得到输出结果。


2.c文件中调用c++文件中的函数。

例如a.c文件调用test.cpp文件中的fun函数。

<span style="font-family: Arial, Helvetica, sans-serif;">//test.cpp</span>
extern "C" int fun(int a, int b){
    return a+b;
}



//a.c
#include <stdio.h>
#include "test.h"

int main(){
    int sum = fun(2,3);
    printf("sum=%d\n",sum);
    return 0;
}

编译方式:g++ -c test.cpp -o test.o

gcc -c a.c -o a.o

g++ -o a a.o test.o

运行: ./a

总结:

1. extern "C"的含义是一种约定,表明编译和链接的时候按照c的风格进行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值