Makefile(一)

规则

1. 写一个最简单的Makefile文件

我们先写一个 hello.c程序,程序如下:

#include <stdio.h>

int main(void)

{

       printf("helloworld!\n");

       return0;

}

在gcc环境下使用如下命令进行编译生成可执行文件:

gcc hello.c -o hello

可是我不想每次改文件后都输入一次这个命令,能不能有种方法把这个命令记下来,我下次改文件后,直接调用命令就行,如果所需要的命令特别多呢,改一个文件后再敲一下所有的命令?这就是Makefile的由来,为了工程编译更加简便。如何写一个Makefile?

首先需要知道Makefile的基本结构:

目标: 依赖文件

       命令(注:命令前必须是tab键)

按照基本规则一一对应就行。

建立Makefile文件,在文件中写入如下规则:

Hello: hello.c

       gcchello.c -o hello

这就是我们写的最简单的Makefile文件。通过make 编译就行。

2.  写一个复杂一点的Makefile文件

这里有一个工程,工程中的文件如下:

animal.c human.c  robot.c  my.h  world.c(各个文件原码在附录中)

工程目的: 通过world.c执行animal.c 、human.c 、robot.c中的函数

没有Makefile需要一条一条输入gcc命令命令如下:

gcc animal.c -c -o animal.o

gcc human.c -c -o human.o

gcc robot.c -c -o robot.o

gcc world.c -c -o world.o

gcc animal.o human.o robot.o world.o -oworld

运行world文件 ./ world

animal world!

human world!

robot world!

如果编写Makefifle需要这样写:

world: world.o robot.o human.o animal.o

       gccworld.o robot.o human.o animal.o -o world

animal.o: animal.c

       gccanimal.c -c -o animal.o

human.o: human.c

       gcchuman.c -c -o human.o

robot.o: robot.c

       gccrobot.c -c -o robot.o

world.o: world.c

       gccworld.c -c -o world.o


clean:

        rm world world.o robot.o human.o animal.o


注意要生成的可执行文件写在最上面。如果想要删除可执行文件和所有的中间目标文件,可以“make clean”命令,如果直接make的话,Makefile会找到第一个目标,如果是make + 目标的话,Makefile会找到对应的目标去执行。

如果我们的工程特别宏大,含有的C文件不计其数比如Linux系统,那我们是否可以简写Makefile呢?比如上面很多重复性的内容用一句概括,这就需要进一步了解Makfile规则。

附录:

animal.c

#include "my.h"

int animal(void)

{

       printf("animalworld!\n");

       return0;

}

human.c

#include "my.h"

int human(void)

{

       printf("humanworld!\n");

       return0;

}

robot.c

#include "my.h"

int robot(void)

{

       printf("robotworld!\n");

       return0;

}

my.h

#ifndef _MY_H

#define _MY_H

#include <stdio.h>

int animal(void);

int robot(void);

int human(void);

#endif

world.c

#include "my.h"

int main(int argc, const char *argv[])

{

       animal();

       human();

       robot();

       return0;

}


猜你喜欢

转载自blog.csdn.net/weixin_42048417/article/details/80207163
今日推荐