C和C++相互调用

本文详细解析了C调用C++和C++调用C的技术细节,包括如何在头文件中添加特定代码以实现跨语言调用。
一.C调用C++

main.c

#include <stdio.h>

#include "Test1.hpp"

int main(int argc, const char * argv[]) {
    printf("%d\n",b());

    return 0;
}

Test1.hpp

#ifndef Test1_hpp
#define Test1_hpp

#include <stdio.h>

#ifdef __cplusplus
extern "C"{
#endif

int b();

#ifdef __cplusplus
}
#endif

#endif /* Test1_hpp */

Test1.cpp


#include "Test1.hpp"

int b()
{

    return 88;
}


二.C++调用C

main.cpp

#include <iostream>
#include <stdio.h>
#include "Test.h"

int main(int argc, const char * argv[]) {

    printf("%d",a());
    return 0;
}

Test.h


#ifndef Test_h
#define Test_h

#include <stdio.h>

#ifdef __cplusplus
extern "C"{
#endif

int a();

#ifdef __cplusplus
}
#endif

#endif /* Test_h */

Test.c

#include "Test.h"
 int a()
{
    return 3;
}




总的来说,就是在相关的头文件中添加了如下代码:

#ifdef __cplusplus
extern "C"{
#endif

......(一些方法或者变量的定义,可以让别的调用)
eg:int a();


#ifdef __cplusplus
}
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值