您的位置:首页 > 运维架构 > Linux

Makefile万能写法(gcc程序以及arm-linux-gcc程序)-转

2016-01-16 15:32 711 查看
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://7071976.blog.51cto.com/7061976/1322211

在linux下使用gcc 编译时,Makefile的万能写法 ,每次只需更改要生成的目标文件名称(test)尽可:

 

1

2

3

4

5

6

7

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名称即可

1

2

3

4

5

6

7

8

9

10

11

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的规则 


1

2

3

4

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 = 1
    b = 2
    c := $(a) 3
    d = 4
    d ?= 5
    b += 6
  结果:
    a=1
    c=1 3
    d=4
    b=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。相应的程序名称相应修改

 

1

2

3

4

5

6

7

8

9

10

11

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: