Makefile文件的编写

来源:互联网 发布:删除数据库 drop 编辑:程序博客网 时间:2024/05/16 02:36

博客内容来源:网络、书籍和自己整理补充

现在有一个helloworld.c文件,编写一个Makefile,要求实现生成helloworld可执行文件,并实现install,uninstall ,clean目标(平台不限)

Makefile文件由以下三个部分组成:需要生成的目标文件(target file)、生成目标文件所需要的依赖文件(dependency file)、生成目标文件的编译规则命令行(command)

target file:dependency file

<Tab>command

第一种Makefile文件编写方式:标准版

helloworld:helloworld.o

    gcc helloworld.o -o helloworld

helloworld.o:helloworld.c

    gcc -c helloworld.c -o helloworld.o

clean:

    rm -rf *.o helloworld

install:

    mkdir /home/mm

    cp helloworld /home/mm

uninstall:

    rm -rf /home/mm

-->make

-->make clean

-->make install

-->make uninstall

第二种Makefile文件编写方式:高配版

OBJS = helloworld.o

CC = gcc

CFLAGS = -Wall -O1 -g

helloworld:$(OBJS)

    $(CC)  $(OBJS) -o helloworld

helloworld.o:helloworld.c

    $(CC)  $(CFLAGS) -c helloworld.c

clean:

    rm -rf *.o helloworld

helloworld_dir = /home/mm

install:

    mkdir $(helloworld_dir)

    cp helloworld $(helloworld_dir)

uninstall:

    rm -rf $(helloworld_dir)

-->make

-->make clean

-->make install

-->make uninstall

第三种Makefile文件编写方式:尊享版

OBJ = helloworld.o

CC = gcc

CFLAGS = -wall -O1 -g

.PHONY:all

all:helloworld $(OBJS)

helloworld:$(OBJS)

    $(CC) $(OBJS) -o helloworld

helloworld.o:helloworld.c

    $(CC) $(CFLAGS) -c helloworld.c

.PHONY:clean

clean:

    rm -rf $(OBJS) helloworld

helloworld_dir = /home/mm

.PHONY:install

install:

    mkdir $(helloworld_dir)

    cp helloworld $(helloworld_dir)

.PHONY:uninstall

uninstall:

     rm -rf $(helloworld_dir)

-->make all:运行命令“make all”后,make会把all看成最终的目标。由于伪目标和真实目标一样都有依赖文件,所以make会更新all的依赖文件helloworld、helloworld.o

-->make clean:运行命令“make clean”后,make会执行命令“rm -rf helloworld $(OBJS)”

-->make install:运行命令“make install”后,make会顺序执行“mkdir $(helloworld_dir)"和“cp helloworld $(helloworld_dir)”,把helloworld文件复制到helloworld_dir变量指定的目录中去

-->make uninstall:运行命令“make uninstall”后,make会执行命令“rm -rf $(helloworld)”,这样就可以把变量helloworld_dir指定的目录以及目录中的文件全部删除

希望能对大家有帮助!谢谢阅读!

0 0