rule
1. Write the simplest Makefile
Let's write a hello.c program first, the program is as follows:
#include <stdio.h>
int main(void)
{
printf("helloworld!\n");
return0;
}
Use the following command to compile and generate an executable file in the gcc environment:
gcc hello.c -o hello
But I don't want to enter this command every time I change the file. Is there a way to write down this command? After I change the file next time, I can just call the command directly. If there are too many commands needed, after changing a file Knock out all the commands again? This is the origin of Makefile, in order to make project compilation easier. How to write a Makefile?
First you need to know the basic structure of Makefile:
target: dependency file
Command (Note: The tab key must be before the command)
Just follow the basic rules.
Create a Makefile and write the following rules in the file:
Hello: hello.c
gcchello.c -o hello
This is the simplest Makefile we've ever written. Just compile it with make.
2. Write a complex Makefile
Here is a project, and the files in the project are as follows:
animal.c human.c robot.c my.h world.c (the original code of each file is in the appendix)
Project purpose: Execute functions in animal.c, human.c, robot.c through world.c
Without Makefile, you need to enter the gcc command one by one. The command is as follows:
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
run the world file ./world
animal world!
human world!
robot world!
If you write Makefifle you need to write:
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
Note that the executable file to be generated is written at the top. If you want to delete the executable file and all intermediate target files, you can use the "make clean" command. If you make directly, the Makefile will find the first target. If it is make + target, the Makefile will find the corresponding target to execute.
If our project is very large and contains countless C files, such as Linux systems, can we abbreviate Makefile? For example, a lot of repetitive content above is summarized in one sentence, which requires further understanding of Makfile rules.
appendix:
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;
}