Why would you useextern "C"

In C++ development, because C, C++ compilation rules are different. The C++ compiler function method uses mangle’s technique.

void func(int age) {}void func(int age, int height) {}/* If these two functions are called, function overloading is not allowed in C, so why is it allowed in C++? The mangle technique is used in C++, where the names of overloaded functions are combined with the representation of custom rules in the compiler, and the compiled function names are different. For example func(int age) -> func_int(int age) func(int age, int height) -> func_int_int(int age, int height) */
Copy the code

This technique is not available in C, so if we want to call some API developed in C, we need to use extern “C” to decorate C function declarations.

extern "C"usage

  • I’m just going to put it in front of the functionextern "C"The keyword
extern "C" void fun(a) {
	printf("test");
}
Copy the code
  • If there is a function declaration and implementation, let the function declaration beextern "C"Modifier, function implementation may not be modified
extern "C" void func(a);
void func(a) {
	cout << "func()" << endl;
}
Copy the code
  • If there are multiple functions to beextern "C"Modifier, can be directly wrapped with {}
extern "C" {
	void func(a);
	void func1(a);
}
void func(a) {
	cout << "func()" << endl;
}
void func1(a) {
	cout << "func1()" << endl;
}
Copy the code

Custom C function library

Extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C” extern “C Just use this function.

// Define sum in the sum.h file
extern "C" {
	int sum(int a, int b);
}

int sum(int a, int b) {
	return a + b;
}

// Include the library in the main.cpp file and you can use it directly
int main(a)
{
	cout << sum(1.2) < <endl;
	getchar();
}
Copy the code

Another problem with this definition, however, is that the library cannot be called from a C file

extern "C"

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

extern "C" {
	int sum(int a, int b);
}

int sum(int a, int b) {
	return a + b;
}

void main(a) {
	printf("%d", sum(3.4));
}
Copy the code

So we need to define the sum library with some rules that extern “C” keywords when called by C++, and remove the extern “C” keywords when called by C++.

//sum.h file declaration
#ifndef __SUM_H
#define __SUM_H

#ifdef __cplusplus
extern "C" {
#endif
    int sum(int a, int b);
#ifdef __cplusplus
}
#endif
#endif

//sum.c file implementation
#include "sum.h"
int sum(int a, int b) {
	return a + b;
}
Copy the code

The __cplusplus macro is unique to C++. It will define the macro in advance when loading the C++ file, so we just need to determine whether the macro is in the file, if it is C++ calling, if it is NOT C language, so we can solve the problem of mixing calls.