extern“C” {} 和__cplusplus小结

1.extern “C” {} 和 __cplusplus的作用

上面两种关键字,都是为了实现C++与C兼容的

1.1 extern“C”{}       的作用

extern “C”是用来在C++程序中声明或定义一个C的符号,比如:

extern "C"{
//函数签名
int  get_hw(int, int);
...
}

//上面的代码,C++编译器会将在extern “C”的大括号内部的代码当做C语言来处理

上面的代码,如果编译时选择C++编译器(如g++), 那么程序会将extern "C"的大括号内部的代码当作C语言的代码处理,即编译会被链接到C标准库。

1.2 __cplusplus    的作用

首先,__cplusplus是cpp中的自定义宏,那么定义了这个宏的话表示这是一段cpp的代码,也就是说:如果这是一段cpp的代码,那么加入extern"C"{和}  以C的方式处理其中的 C 代码(编译将会被链接到C标准库)。

1.3 示例:

例如有以下文件:fun.c   fun.h    main.cpp    test.cpp    test.h

fun.h

#ifndef  _FUN_H_
#define  _FUN_H_

extern "C" {
int  get_fun(int);
}

fun.c

#ifndef _FUN_H_
#include "fun.h"
#endif

int get_fun(){
    return 10;
}

test.h

#ifndef _TEST_H_
#define _TEST_H_

void  test();

#endif

test.cpp

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

#ifdef __cplusplus 
extern "C" {
#endif

#include "fun.h"

#ifdef __cplusplus
}
#endif
//以上内容可以放在test.h中

void test(){
    printf("fun:%d\n", get_fun());
}

main.cpp

#include "test.h"

int main(int argc, char **argv){
    test();
    return 0;
}

makefile文件:

all:main.o test.o fun.o
    g++ -o all main.o test.o fun.o
main.o:
    g++ -c main.cpp
test.o:
    g++ -c test.cpp
fun.o:
    gcc -c fun.c

clean:
    rm -f *.o all

从而实现了C与C++的混合编译。

详细请参考:

https://blog.youkuaiyun.com/ma52103231/article/details/72890627

https://blog.youkuaiyun.com/kunluo/article/details/72834525

https://zhuge.blog.youkuaiyun.com/article/details/81152891?utm_medium=distribute.pc_relevant_t0.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-1.control

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值