Linux 的makefile的撰写

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/90084569

一 点睛

makefile中会定义一系列规则,指定哪些文件先编译,哪些文件后编译,哪些文件需要重新编译,甚至于进行更复杂的功能操作。

makefile带来的好处就是“自动化编译”,一旦写好,只需要一个make命令,整个工程完全自动编译。

make命令是一个命令工具,是一个解释makefile中指令的命令工具。

makefile关系到整个工程的编译规则。

makefile就像一个shell脚本一样,其中也可以执行操作系统的命令。

二 实战

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 编译

[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 说明

1 用make -j带一个参数,可以把项目进行并行编译。

参考:https://blog.csdn.net/a_little_a_day/article/details/78251928

2 make clean用于清理编译出的内容。

3 make参数"-s"或"--slient"则是全面禁止命令的显示。

参考:https://blog.csdn.net/pzhw520hchy/article/details/80260848

参考:https://blog.csdn.net/yimingsilence/article/details/51690619

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/90084569