C/C++混合编程 #ifdef __cplusplus extern "C" {...}

C用gcc方式编译;C++用g++方式编译。

C/C++混合编程需要关键字extern。

c++调用c比较简单,只需要extern;|| 而c调用c++则需要考虑c++的函数重载等功能,需要使用 #ifdef __cplusplus extern "C" {...}

一、extern“C”的作用(最重点)

    1. extern "C"的真实目的是实现类C和C++的混合编程extern “C”是由C++提供的一个连接交换指定符号,用于告诉C++这段代码是C函数。extern “C”后面的函数不使用的C++的名字修饰,而是用C这是因为C++编译后库中函数名会变得很长,与C生成的不一致,造成C++不能直接调用C函数。

二、extern“C”与__cplusplus(主要是c调用C++时使用)

#ifdef __cplusplus
extern "C" {
#endif
//·················
//之间是需要指明用C方式编译的代码;原本属于C++的代码
//·················
#ifdef __cplusplus
}
#endif


    cplusplus即"C++",用于C++文档的头文件中,上面代码的意思是:如果是C++文件(*.cpp)后缀,则使用extern “C”,在C++项目中应用的非常广泛。即使用gcc编译器编译,函数名为C类型如_foo

三、对实例进行编译说明

1、 C++调用C

有由C语言编写的add()、sub()程序,并将其生成静态库:

//add.h
#ifndef __ADD_H__
#define __ADD_H__
int add(int, int);
#endif /* __ADD_H__ */

//add.c
#include "add.h"
int add(int a, int b)
{
    return a + b;
}
//------------------------------------------------
//sub.h
#ifndef __SUB_H__
#define __SUB_H__
int sub(int, int);
#endif /* __SUB_H__ */

//sub.c
#include <stdio.h>
#include "sub.h"
int sub(int a, int b)
{
    printf("%d - %d = %d\n", a, b, a - b);
    return 0;
}

编译生成静态库lib**.a或动态库lib**.so

#静态库
$ gcc -c add.c
$ gcc -c sub.c
$ ar cqs libadd.a *.o

#动态库
$ gcc -shared -fPIC *.o -o libadd.so

但是主函数调用这两个函数时是用C++编写的->>>>>>>>>>> 用g++编译

//main.cpp
#include "add.h"
#include "sub.h"
#include <stdio.h>
int main(void)
{
    int c = add(1, 6);
    sub(8, 2);
    printf("c = %d\n", c);
    return 0;
}

用g++编译,则会报错----->>>>>>>>>>>>>>>>未定义add、sub函数

所以要加上关键字extern,main函数修改如下:将用C语言编写的头文件用关键字extern的花括号括起来

//使得add.h、sub.h里面的代码用c语言的方式去编译
extern "C"{
#include "add.h"
#include "sub.h"
}
#include <stdio.h>
int main(void)
{
    int c = add(1, 6);
    printf("c = %d\n", c);
    return 0;
}

2、 C调用C++

参考博客后面部分 https://blog.csdn.net/qq_29344757/article/details/73332501