Linux的Makefile小例子

本文介绍了一个使用C语言进行模块化编程的例子,包括main.c作为主文件调用hello.c、here.c和bye.c三个独立模块,以及如何通过Makefile进行自动化构建和清理。展示了C语言函数声明与定义的分离,以及Makefile中目标和依赖关系的设置。

main.c

#include <stdio.h>
#include <sys/types.h>
#include "hello.h"

int main(void)
{
	 hello();
	 here();
	 bye();
     exit(0);	
}

hello.h

void hello();
void here();
void bye();

hello.c

#include <stdio.h>

void hello()
{
	printf("Hello!\n");
}

here.c

#include <stdio.h>

void here()
{
	printf("I'm here\n");
}

bye.c

#include <stdio.h>

void bye()
{
	printf("Goodbye!\n");
}

Makefile

CC = gcc

PROG = myhello
HRDS = hello.h
SRCS = main.c hello.c here.c bye.c
CFLAG = -g -Wall

OBJS = $(SRCS:*.c=*.o)

$(PROG) : $(OBJS)
	$(CC) $(OBJS) -o $(PROG)
main.o : main.c hello.h
hello.o : hello.c
here.o : here.c
bye.o : bye.c



clean: 
	rm -f $(OBJS)

运行结果

Makefile还有另一种写法

main:main.o hello.o here.o bye.o
main.o:main.c
	gcc -c main.c -o main.o
hello.o:hello.c
	gcc -c hello.c -o hello.o
here.o:here.c
	gcc -c here.c -o here.o
bye.o:bye.c
	gcc -c bye.c -o bye.o

.PHONY:clean

clean:
	-rm -rf *.o

运行结果:

注意!在Makefile里,缩进是Tab键实现的,否则会报错“*** missing separator.  Stop.”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值