本篇文章主要讨论如何实现C的模块化编程
这里所指的模块化编程是利用头文件的形式,将一个项目代码划分到多个文件里面,并使用make进行编译处理。
我们先来从主文件中分离函数,为此我们需要两个文件,Main.c和CMath.c
/*------------------------------------------
Main.c
------------------------------------------*/
#include <stdio.h>
double Abs(double x);//绝对值
int CubePow(int a) ;//立方数
int main () {
double d = -2.0;
printf("%f\n",Abs(d) );
printf("%d\n",CubePow(2) );
return 0;
}
/*------------------------------------------
CMath.c
------------------------------------------*/
double Abs(double x) {
return x * (-1);
}
int CubePow(int a) {
return a*a*a;
}
将代码存放在两个地方,需要将两个文件链接起来并执行
mkdir exe
gcc -o exe/Main Main.c CMath.c
exe/Main
#运行结果
#2.000000
#8
在上面两个文件的基础上,再引入头文件,将函数的原型从主函数分离出来,具体实现方式请看下面
------------------------------------------*/
#include <stdio.h>
#include "CMath.h"
int main () {
double d = -2.0;
printf("%f\n",Abs(d) );
printf("%d\n",CubePow(2) );
return 0;
}
/*------------------------------------------
CMath.h
------------------------------------------*/
#ifndef _Cmath_H // #ifndef 后面的值可以自己定义,但要跟下一行保持一致,这一步是为了防止CMath.h文件被重复导入
#define _CMath_H
double Abs(double x);//绝对值
int CubePow(int a) ;//立方数
#endif
/*------------------------------------------
CMath.c
------------------------------------------*/
#include "CMath.h"
double Abs(double x) {
return x * (-1);
}
int CubePow(int a) {
return a*a*a;
}
将三个文件链接起来并执行
gcc -o exe/Main Main.c CMath.c CMath.h
exe/Main
#运行结果
#2.000000
#8
好了,模块化的工作这样结束了。
不过需要注意的是,这篇文章并未讲解extern和static的用法,具体请看相关书籍,使用static来决定函数或者变量是否可以被其他文件的代码访问。
这里提供另外一种方式运行编译指令,这种方式需要一种文件Makefile,具体Makefile教程可以观看 陈皓-跟我一起写Makefile
run: Main.c CMath.c CMath.h
gcc -o exe/Main Main.c CMath.c CMath.h
exe/Main
#将上面的内容写到Makefile文件内
vim Makefile
#运行
make