linux平台makefile文件的编写基础篇目的:基本掌握了 make 的用法,能在Linux系统上编程。环境:Linux系统,或
linux平台makefile文件的编写基础篇
目的:基本掌握了 make 的用法,能在Linux系统上编程。
环境:Linux系统,或者有一台Linux服务器,通过终端连接。一句话:有Linux编译环境。
准备:准备三个文件:file1.c, file2.c, file2.h
file1.c:
#include <stdio.h>#include "file2.h"int main(){printf("print file1 $$$$$$$$\n");File2Print();return 0;}
file2.h:
#ifndef FILE2_H_#define FILE2_H_#ifdef __cplusplusextern "C" {#endifvoid File2Print();#ifdef __cplusplus}#endif#endif
file2.c:
#include "file2.h"void File2Print(){printf("Print file2 $$$$$\n");}
先来个例子:有这么个makefile文件。(文件和makefile在同一目录)
helloworld: file1.o file2.ogcc file1.o file2.o -o helloworldfile1.o: file1.c file2.hgcc -c file1.c -o file1.ofile2.o: file2.c file2.hgcc -c file2.c -o file2.oclean:rm -rf *.o helloworld
一个makefile主要含有一系列的规则,如下:
A: B(tab)<command>(tab)<command>
每个命令行前都必须有tab符号。
上面的makefile文件目的就是要编译一个helloworld的可执行文件。让我们一句一句来解释:
helloworld : file1.o file2.o:helloworld依赖file1.o file2.o两个目标文件。
gcc File1.o File2.o -o helloworld:编译出helloworld可执行文件。-o表示你指定 的目标文件名。
file1.o : file1.c:file1.o依赖file1.c文件。
gcc -c file1.c -o file1.o:编译出file1.o文件。-c表示gcc 只把给它的文件编译成目标文件, 用源码文件的文件名命名但把其后缀由“.c”或“.cc”变成“.o”。在这句中,可以省略-o file1.o,编译器默认生成file1.o文件,这就是-c的作用。
file2.o : file2.c file2.h
gcc -c file2.c -o file2.o
这两句和上两句相同。
clean:
rm -rf *.o helloworld
当用户键入make clean命令时,会删除*.o 和helloworld文件。
如果要编译cpp文件,只要把gcc改成g++就行了。
写好makefile文件,在命令行中直接键入make命令,就会执行makefile中的内容了。
到这步我想你能编一个Helloworld程序了。