现在的位置: 首页 > 综合 > 正文

makefile的使用总结

2018年03月21日 ⁄ 综合 ⁄ 共 1595字 ⁄ 字号 评论关闭

  需要注意的几点:

1在一个makefile中定义的变量不能自动传递到下层的makefile,即使使用export关键字声明将其传递到子makefile中,也不能对其进行赋值操作。同时在makefile中定义的变量不能够在target的执行命令中进行赋值,只能在全局声明中进行声明,赋值操作。

 

2在编写makefie时,每个目标依赖的不光可以是.a, .o这样的用于编译的文件,也可以是其他的目标,在其他的目标中执行一些脚本之类的,比如创建目录,复制文件等一些操作。

 

3在makefile中可以使用make -Csubdir/,来强制执行子目录下的makefile,使用include /subdir/makefile,包含子目录的makefile,这样的话,就会把子目录的makefile展开在父目录的makefile中。

 

4多使用自动化变量,我们常用的是$@,$<,其中$@是表示每一个生成目标,$<是用来表示每一个依赖目标。下面是其常见用法:

%.o: %.c

         gcc-c $<

对该包含该语句的makefile执行make命令时,系统实际上会根据文件生成多个实际的依赖关系,比如目录subdir下有两个文件test1.c, test2.c则会生成test1.o: test1.c ,test2.o:test2.c这两个依赖关系。

 

5使用在shell中定义的变量时,需要使用$$var来引用该变量,而不是$var

下面是我的一个小例子:

root@localhost:/home/ngos/testmakefile.bak>ls

makefile makefile.bak  ngtos  subdir subdir1  target  test

 

工程分别由test, subdir, subdir1三个目录的源码编译而成,对于每个目录先生成一个.a然后生成一个可执行文件ngtos。

 

主makefile:

         objects= target/test.a  target/subdir.atarget/subdir1.a

dirs=subdir subdir1 test

export count= 1

#all:$(objects) end

 

all: maketarget

         gcc-o ngtos  $(objects)

 

maketarget:

         CROSS_COMPILE=helloword;\

         echo$$CROSS_COMPILE

         fordir in $(dirs); do \

         make-C $$dir/ all;\

         done

 

target/subdir.a:

         make-C subdir/ all

target/subdir1.a:

         make-C subdir1/ all

target/test.a:

         #ar-r test.a test1.o test2.o

         #mvtest.a target/i

         make-C test/ all

%.o:%.c

         gcc-c $<

 

end:

         @echo"@@@@@@@@#####here end!"        

clean:

         rm-f target/*

         -rm-f *.o

         make-C subdir/ clean

         make-C subdir1/ clean   

 

子makefile:

 

all: test.a

         mvtest.a ../target/

 

test.a: test1.o test2.o

         @echo$(@)

         ar-r $(@) test1.o test2.o

 

%.o: %.c

         gcc-c $<

 

clean:

         -rm-f *.o

抱歉!评论已关闭.