The writing of makefile in Linux

Keywords: Makefile shell

A little bit of eye

A series of rules will be defined in the makefile to specify which files are compiled first, which files are compiled later, which files need to be recompiled, or even more complex functional operations.

The advantage of makefile is "automatic compilation". Once written, only one make command is needed, and the whole project will be compiled automatically.

The make command is a command tool that interprets the commands in the makefile.

makefile is related to the Compilation Rules of the whole project.

makefile is like a shell script, which can also execute commands of the operating system.

Two actual combat

1 file1.h

#ifndef FILE1_H_
#define FILE1_H_
#ifdef __cplusplus
    extern "C" {
       #endif
       void File1Print();
       #ifdef __cplusplus
    }
    #endif
#endif

2 file1.cpp

#include <iostream>
#include "file1.h"
using namespace std;
void File1Print(){
    cout<<"Print file1**********************"<<endl;
}

3 file2.cpp

#include <iostream>
#include "file1.h"
using namespace std;
int main(){
    cout<<"Print file2**********************"<<endl;
    File1Print();
    return 0;
}

4 Makefile

helloworld:file1.o file2.o
    g++ file1.o file2.o -o helloworld

file2.o:file2.cpp
    g++ -c file2.cpp -o file2.o

file1.o:file1.cpp file1.h
    g++ -c file1.cpp -o file1.o

clean:
    rm -rf *.o helloworld

5 compilation

[root@localhost charpter04]# cd 0403
[root@localhost 0403]# ll
total 16
-rw-r--r--. 1 root root 140 May  1 08:52 file1.cpp
-rw-r--r--. 1 root root 170 May  1 08:52 file1.h
-rw-r--r--. 1 root root 167 May  1 08:52 file2.cpp
-rw-r--r--. 1 root root 208 May  1 08:52 Makefile
[root@localhost 0403]# make -sj
[root@localhost 0403]# ll
total 36
-rw-r--r--. 1 root root  140 May  1 08:52 file1.cpp
-rw-r--r--. 1 root root  170 May  1 08:52 file1.h
-rw-r--r--. 1 root root 2696 May 10 21:34 file1.o
-rw-r--r--. 1 root root  167 May  1 08:52 file2.cpp
-rw-r--r--. 1 root root 2752 May 10 21:34 file2.o
-rwxr-xr-x. 1 root root 9296 May 10 21:35 helloworld
-rw-r--r--. 1 root root  208 May  1 08:52 Makefile
[root@localhost 0403]# make clean
rm -rf *.o helloworld
[root@localhost 0403]# ll
total 16
-rw-r--r--. 1 root root 140 May  1 08:52 file1.cpp
-rw-r--r--. 1 root root 170 May  1 08:52 file1.h
-rw-r--r--. 1 root root 167 May  1 08:52 file2.cpp
-rw-r--r--. 1 root root 208 May  1 08:52 Makefile

6 description

1. Take a parameter with make-j to compile the project in parallel.

Reference resources: https://blog.csdn.net/a_little_a_day/article/details/78251928

2 make clean is used to clean up the compiled content.

3. The "make" parameter "- s" or "- slient" is the display of the overall disable command.

Reference resources: https://blog.csdn.net/pzhw520hchy/article/details/80260848

Reference resources: https://blog.csdn.net/yimingsilence/article/details/51690619

Posted by MrPotatoes on Wed, 13 Nov 2019 08:19:22 -0800