关于makefile的使用及介绍网上非常多。也有专门的书籍介绍makefile。推荐这本书,是详细介绍makefile的——《跟我一起写makefile》
在这里,我只会简单的介绍makefile的语法。着重写些注意事项。主要是写些例子,帮助大家理解是快速入门。
最简单的就是单文件了。直接编译会更快些,用makefile反倒麻烦,不过这是有助于理解的,循序渐进才能学好的。
好了,不多说,先从Helloworld入手!
//hello.c
#include <stdio.h>
int main()
{
printf("hellow world!");
return 0;
}
我们这个程序的makefile如下:(文件名为Makefile,M大小写无所谓)
hello: hello.o
gcc hello.o -o hello
hello.o: hello.c
gcc -c hello.c -o hello.o
clean:
rm -f *.o
之后直接在终端输入输入make
就完成了。由于本文的侧重是带领大家操作。所以不讲语法和书写规则。详细了解请看推荐的那本书。
下面,我们写个简单的多文件的makefile
//main.c
#include "hello.h"
int main()
{
hello();
return 0;
}
//hello.c
#include "hello.h"
int hello()
{
printf("hello world!\n");
return 0;
}
//hello.h
#include <stdio.h>
int hello();
好了,用main.c hello.c hello.h这三个进行演示,我们的makefile就需要书写如下:
hello: main.o hello.o
gcc main.o hello.o -o hello
main.o: main.c
gcc -c main.c -o main.o
hello.o: hello.c
gcc -c hello.c -o hello.o
clean:
rm -f *.o
好了,今天这个一起来学Makefile(一)算是入门,今后还会有更复杂的学习,包括规范的使用makefile。合理的建立makefile。我会和大家一起分享的。
(就在这里顺便说下吧,书写代码的规范性很重要,最为一个程序员,代码的风格就是你给别人的第一印象,所以平时一定要养成良好的编码风格哦~)