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.csdn.net/ma52103231/article/details/72890627

https://blog.csdn.net/kunluo/article/details/72834525

https://zhuge.blog.csdn.net/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


版权声明:本文为int_t原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。