在linux下使用gcc 编译时,Makefile的万能写法 ,每次只需更改要生成的目标文件名称(test)尽可:
objs := $(patsubst %c, %o, $(shell ls *.c))
test.all:$(objs)
gcc -o $@ $^
%.o:%.c
gcc -c -o $@ $<
clean:
rm -f *.all *.o
在arm交叉编译时的makefile的万能写法,只需更改int.bin,以及int_elf,int.dis名称即可
objs := $(addsuffix .o, $(basename $(shell ls -U *.S *.c)))
int.bin: $(objs)
arm-linux-ld -Ttext 0x00000000 -o int_elf $^
arm-linux-objcopy -O binary -S int_elf $@
arm-linux-objdump -D -m arm int_elf > int.dis
%.o:%.c
arm-linux-gcc -Wall -O2 -c -o $@ $<
%.o:%.S
arm-linux-gcc -Wall -O2 -c -o $@ $<
clean:
rm -f *.bin *_elf *.dis *.o
更多Makefile学习可百度:GUN MAKE 手册
Makefile的规则Makefile的规则:
目标文件:依赖文件
target ... : prerequisites ..
command
target要求
1、要生成的可执行文件或obj文件;
2、也可以是一个执行的动作名称:clean
Makefile执行规则:
1、执行make时,仅当hell.c文件比hello.o文件更新,才会执行命令:arm-linux-gcc -o hello.o hello.c;
2、如果没有hello.o文件也会执行
3、运行 make clean 时,由于clean 没有依赖,它的命令也会被强制执行
makefile赋值:
Makefile中的"="":="、"?="和"+="区别是:"="是直接给变量赋值。":="是将":="右边中包含的变量直接展开给左边的变量赋值。"?="是在该变量没有被赋值 的情况下为其赋值。"+="是给该变量追加值。例:a = 1b = 2c := $(a) 3d = 4d ?= 5b += 6结果:a=1c=1 3d=4b=2 6
使用makefile 编译c程序:
1、一些make函数的巧用
1、$(patsubst pattern, replacement,text)
原理:用replacement替换text中符合格式"pattern" 的字
如:$(patsubst %.c, %.o, b.a.c hello.c helloworld.c)
结果为字符串:b.a.o hello.o helloworld.o
2、$(shell command arguments)
3、$(basename names.....)
原理:抽取除"names...."中每一个文件名中除后缀外的一切字符
比如:
$(basename head.S hello.c helloworld.c)
结果为:head hello helloworld
4、$(addsuffix suffix,names...)
如:$(addsuffix .c, head hello helloworld)
结果为:head.o hello.o hello.o helloworld.o
在linux中编译c程序时写make文件就有一些技巧了
在 arm 嵌入式交叉编译时,就可以这样编写Makefile。相应的程序名称相应修改
objs := $(addsuffix .o, $(basename $(shell ls *.S *.c)))
int.bin: $(objs)
arm-linux-ld -Ttext 0x00000000 -o int_elf $^
arm-linux-objcopy -O binary -S int_elf $@
arm-linux-objdump -D -m arm int_elf > int.dis
%.o:%.c
arm-linux-gcc -Wall -O2 -c -o $@ $<
%.o:%.S
arm-linux-gcc -Wall -O2 -c -o $@ $<
clean:
rm -f *.bin *_elf *.dis *.o