Three simple cases by using makefile---1

I use three parts(make_test0, make_test1, make_test) to progressive introduction simple makefiles apply for project

1.make_test0(directory)

make_test0 ----Makefile
          |----top_main.c
          |----hello.c

(1)hello.c  -----

#include <stdio.h>
int print_hello(){
	printf("hello..........\n");
	return 0;
}

(2)top_main.c-----

#include <stdio.h>
extern int print_hello();
int main(){
	printf("main............\n");
	print_hello();
	return 0;
}

(3)Makefile

CC = gcc
CFLAGS = -c 
OBJS = $(patsubst %.c, %.o, $(wildcard *.c))

.c.o:
	@echo "compile............"
	$(CC) $(CFLAGS) -o $@ $<

obj_main:$(OBJS)
	@echo "obj_main.........."
	$(CC) -o $@ $(OBJS)

.PHONY:clean
clean:
	rm -f obj_main  $(OBJS)

(4)compile results

xxx@xxx-xx-xxx:~/make_test0$ make
compile............
gcc -c  -o hello.o hello.c
compile............
gcc -c  -o main.o main.c
obj_main..........
gcc -o obj_main  hello.o  main.o

2. make_test1

make_test1 ----Makefile
          |----top_main.c
          |----hello.c
          |----include
                     |----hello.h
          |----depend.mk

(1)top_main.c  -->  it is same as make_test0

(2)hello.c        ---> add "hello.h" header file to it.

#include <stdio.h>
#include "hello.h"

int print_hello(void){
	
	printf("hello...%d\n", H_ADD(3,5));
	return 0;
}

(3)hello.h      ---->it locates at include directory

#define H_ADD(a, b) ((a) + (b))
#define H_DEC(a, b) ((a) - (b))

(4)depend.mk

#第一步执行
include $(patsubst %.c, %.d, $(wildcard *.c))

#第二步执行
%.d: %.c									
	@set -e; rm -f $@; \
	$(CC) -M -Iinclude $< > $@.; \
	sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@. > $@;\
	rm -f $@.
	@echo "hello..............."$@

(5)Makefile

#该变量主要用来指定源文件目录,便于查找源文件
VPATH = print_hello 

CC 	 = 	gcc
#该变量主要用来指定头文件目录
LDFLAGS = -lm -DFORK_CHILDREN=1
INCLUDEFLAGS = -Iinclude
#CFLAGS 		= 
CFLAGS = -c -Wall

SRC = 	top_main.c \
	hello.c 			
	  
OBJS = $(SRC:.c=.o)

.c.o:
	@echo "compile............."$@
	$(CC) $(CFLAGS) $(INCLUDEFLAGS) -o $@ $<

#第三步执行
obj_main: $(OBJS)
	@echo "obj_main"
	$(CC) $(LDFLAGS) -o $@ $(OBJS)
	
include depend.mk

.PHONY: clean
clean:
	rm -f *.d *.o obj_main

(6) compile results

xxx@xxx-xx-xxx:~/make_test1$ make
depend.mk:2: hello.d: No such file or directory
depend.mk:2: top_main.d: No such file or directory
hello...............top_main.d
hello...............hello.d
compile.............top_main.o
gcc -c -Wall -Iinclude -o top_main.o top_main.c
compile.............hello.o
gcc -c -Wall -Iinclude -o hello.o hello.c
obj_main
gcc -lm -DFORK_CHILDREN=1 -o obj_main top_main.o hello.o
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值