由于第三方框架/库可能是C编写的,用C++调用C,C调用C,两者混合编程
1.main.cpp源文件:包含程序执行入口的main函数,main.cpp调用math.c
#include<iostream>
using namespace std;
//#define __cplusplus为定义C++环境的宏,默认不写
/*
第三方框架/库,可能是C语言写的,C++调用C
*/
/*
//方法一: 不添加头文件
extern "C"{
int sum(int v1, int v2);
int delta(int v1, int v2);
}
*/
//方法二:添加头文件
#include "math.h"
#include "other.h"
#include "test.h"
//extern "C" void other();
int main() {
other();//调用oher
cout << sum(10, 20) << endl;
cout << delta(10, 20) << endl;
test();//调用test
getchar();
return 0;
}
2.math.c源文件:要调用的math.c文件,实现求和求差
//c文件存放函数的实现
#include "math.h"
int sum(int v1, int v2) {
return v1 + v2;
}
int delta(int v1, int v2) {
return v1 - v2;
}
3.math.h头文件:用来对math.c中的待调用函数声明
//header file:存放函数的声明
#ifndef __MATH_H //
#define __MATH_H //上行、本行和末行为一个整体,防止头文件内容被重复包含, 等同于#pragma once。前者可作用于文件局部或整个文件,后者作用于整个文件
#ifdef __cplusplus
extern "C"{
#endif
int sum(int v1, int v2);
int delta(int v1, int v2);
#ifdef __cplusplus
}
#endif//__cplusplus
#endif //!__MATH_H
4.other.c源文件:可能存在C调用C的情况,other.c文件调用math.c
#include "math.h"
#include<stdio.h>
void other() {
//sum(10, 20);
printf("other - %d\n", sum(10, 20));
}
5.other.h头文件:对other.c文件声明(为了在main函数中调用other.c)
#ifndef __OTHER_H
#define __OTHER_H
extern "C"{
void other();
}
#endif //!__OTHER_H
6.test.cpp源文件:除去main.cpp外可能调用math.c的cpp文件
#include "math.h"
#include <iostream>
using namespace std;
void test() {
cout <<sum(10, 10)<<endl;
}
7.test.h头文件:声明test.cpp中的test函数(为了在main函数中调用)
#ifndef __TEST_H
#define __TEST_H
void test();
#endif //!__TEST_H
思路:
1)想在main函数中调用math.c中的求和与求差函数。因此,需要建立math.h对math.c中的两个函数进行声明,并把math.h包含到main.cpp中(等价于不建立math.h的情况下,直接在main.cpp中对这两个函数声明)。但问题是,这两个函数实现在C文件中,main.cpp属于C++环境,此时需要加入extern “C”,使其按照C的方式编译。
2)想在other.c中调用math.h中的两个函数,在main中调用other.c中的函数。因此,在math.h中加入条件编译(对extern "C"是否使用进行判断)。为了在main中调用other.c中的函数,建立了other.h对other.c的函数进行声明。
3)想在test.cpp中调用math.h,在main中调用test.cpp中的函数。注意extern "C"的使用和包含的声明,道理同上,需要细品。
-
所有文件:
-
文件逻辑关系:
-
最后打印的结果如下: