被extern "C"修饰的代码会按照C语言的方式去编译
extern "C" void func(){}
extern "C" void func(int v) {}
extern "C" {
void func() { }
void func(int v) { }
}
如果函数同时有声明和实现,要让函数声明被extern "C"修饰,函数实现可以不修饰
extern "C" void func();
extern "C" void func(int v);
extern "C" {
void func();
void func(int v);
}
void func() {
cout << "func()" << endl;
}
void func(int v) {
cout << "func(int v)" << endl;
}
1.C++在调用C语言API时,需要使用extern "C"修饰C语言的函数声明
2.有时也会在编写C语言代码中直接使用extern “C” ,这样就可以直接被C++调用
我们经常使用#ifndef、#define、#endif来防止头文件的内容被重复包含
◼ #pragma once可以防止整个文件的内容被重复包含
◼ 区别
#ifndef、#define、#endif受C\C++标准的支持,不受编译器的任何限制
有些编译器不支持#pragma once(较老编译器不支持,如GCC 3.4版本之前),兼容性不够好
#ifndef、#define、#endif可以针对一个文件中的部分代码,而#pragma once只能针对整个文件
//==================math.h===================
#ifndef __MATH_H
#define __MATH_H
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
int sum(int v1, int v2);
int delta(int v1, int v2);
int divide(int v1, int v2);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // !__MATH_H
//==================math.c===================
#include "math.h"
// _sum
int sum(int v1, int v2) {
return v1 + v2;
}
// _delta
int delta(int v1, int v2) {
return v1 - v2;
}
int divide(int v1, int v2) {
return v1 / v2;
}
//==================other.h=================
#pragma once
void other1();
#ifndef __OTHER_H
#define __OTHER_H
void other2();
#endif // !__OTHER_H
//=======================other.c=================
#include "math.h"
#include <stdio.h>
void other() {
printf("other - %d\n", sum(10, 20));
}
//=================main.cpp=================
#include <iostream>
using namespace std;
#include "other.h"
#include "math.h"
#include "test.h"
int main() {
cout << sum(10, 20) << endl;
cout << delta(30, 20) << endl;
cout << divide(30, 3) << endl;
getchar();
return 0;
}