C模块化开发

本篇文章主要讨论如何实现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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值