Linux - write the makefile

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/starter_____/article/details/90737544

First, the preparation of the source file

/* main.c */
#include "mytool1.h"
#include "mytool2.h"
int main(int argc,char **argv)
{
	mytool1_print("hello");
	mytool2_print("hello");
}
/* mytool1.h */
#ifndef _MYTOOL_1_H
#define _MYTOOL_1_H
	void mytool1_print(char *print_str);
#endif

/* mytool2.h */
#ifndef _MYTOOL_2_H
#define _MYTOOL_2_H
	void mytool2_print(char *print_str);
#endif
/* mytool1.c */
#include "mytool1.h"
#include <stdio.h>
void mytool1_print(char *print_str)
{
	printf("This is mytool1 print %s\n",print_str);
}

/* mytool2.c */
#include "mytool2.h"
#include <stdio.h>
void mytool2_print(char *print_str)
{
	printf("This is mytool2 print %s\n",print_str);
}

Since this program is very short, so we can compile:

$ gcc -c main.c -o main.o
$ gcc -c mytool1.c -o mytool1.o
$ gcc -c mytool2.c -o mytool2.o
$ gcc -o main main.o mytool1.o mytool2.o

Write the makefile

But if we want to repeat modify the contents of a file, you do not want multiple compilations? This time they had a makefile to solve this problem:

1, makefile complete form:

main:main.o mytool1.o mytool2.o
	gcc -o main main.o mytool1.o mytool2.o
main.o:main.c mytool1.h mytool2.h
	gcc -c main.c -o main.o
mytool1.o:mytool1.c mytool1.h
	gcc -c mytool1.c -o mytool1.o
mytool2.o:mytool2.c mytool2.h
	gcc -c mytool2.c -o mytool2.o

2, makefile Simplification of the form:

  • $ @ - the target file
  • $ ^ - all dependent files
  • $ <- The first relies file.
main:main.o mytool1.o mytool2.o
	gcc -o $@ $^
main.o:main.c mytool1.h mytool2.h
	gcc -c $<  -o $@
mytool1.o:mytool1.c mytool1.h
	gcc -c $< -o $@
mytool2.o:mytool2.c mytool2.h
	gcc -c $< -o $@

3, makefile simplest form of Default:

main:main.o mytool1.o mytool2.o
	gcc -o $@ $^
..c.o:
	gcc -c $<

4, execution makefile

$ make

Guess you like

Origin blog.csdn.net/starter_____/article/details/90737544