Makefile编写之小弟我见
Makefile
=================================================================
例1.写一个简单的Makefile
源文件:hello.c hello.h
-----hello.c文件----
#include"hello.h"
int main()
{
printf("this is hello world\n");
return 0;
}
-----hello.h文件-----
#ifndef HELLO_HH_
#define HELLO_HH_
#include <stdio.h>
#endif
------Makefile文件-----
hello : hello.o
gcc hello.o -o hello
hello.o : hello.c hello.h
gcc -c hello.c -o hello.o
.PHONY : clean
clean:
rm -r *.o
编译:执行<1> make <2>./hello
==================================================================
例2.写三个.c 和一个.h
源文件:file.h main.c file1.c file2.c
------file.h文件---------
#ifndef FILE_HH_
#define FILE_HH_
#include <stdio.h>
void foo();
void goo();
#endif
-------file1.c文件-----
#include "file.h"
void foo()
{
printf("this is foo()\n");
}
------file2.c文件-------
#include "file.h"
void goo()
{
printf("this is goo()\n");
printf("this is invoking foo()");
foo();
}
-------main.c文件--------
#include "file.h"
int main()
{
foo();
goo();
return 0;
}
------Makefile文件------
app : main.o file1.o file2.o
gcc main.o file1.o file2.o -o app
main.o : main.c file.h
gcc -c main.c -o main.o
file1.o : file1.c file.h
gcc -c file1.c -o file1.o
file2.o : file2.c file.h
gcc -c file2.c -o file2.o
.PHONY : clean //创建伪目标即执行make clean 来清除 *.o 文件
clean :
rm -rf *.o
编译:执行<1> make <2>./app
==============================================================
例3.使用变量创建Makefile
修改例2的Makefile文件
------Makefile文件------
OBJS = main.o file1.o file2.o
CC = gcc
CFLAGS = -Wall -g -O2
APP =app
$(APP) : $(OBJS)
$(CC) $(OBJS) -o $(APP)
main.o : main.c file.h
$(CC) $(CFLAGS) -c main.c -o main.o
file1.o : file1.c file.h
$(CC) $(CFLAGS) -c file1.c -o file1.o
file2.o : file2.c file.h
$(CC) $(CFLAGS) -c file2.c -o file2.o
.PHONY : clean
clean :
rm -rf *.o
===============================================================
例4使用自动变量创建Makefile
只需记住三个常用变量:
<1> $@ 目标文件的完整名称 <2> $^ 所有不重复的目标依赖文件,以空格分开 <3> $< 第一个依赖文件名称
(1)修改例2的Makefile文件
-------Makefile文件--------
OBJS = main.o file1.o file2.o
CC = gcc
CFLAGS = -Wall -O -g
APP =app
$(APP) : $(OBJS)
$(CC) $^ -O $@
main.o : main.c file.h
$(CC) $(CFLAGS) -c $< -o $@
file1.o : file1.c file.h
$(CC) $(CFLAGS) -c $< -o $@
file2.o : file2.c file.h
$(CC) $(CFLAGS) -C $< -O $@
.PHONU : clean
clean :
rm -rf *.o
(2)修改例2的Makefile文件
-------Makefile文件--------
OBJS = main.o file1.o file2.o #target file
CC = gcc #compiler
LDFLAGS= # "-L link libraries "or "-I include"
CFLAGS = -Wall -g -O2 #compiler parameter
APP = app #execution file
$(APP) : $(OBJS)
$(CC) $(LDFLAGS) $^ -o $@
%.o : %.c
$(CC) -c $(CFLAGS) $^
.PHONY : clean
clean:
rm -rf $(OBJS) $(APP) *.gch
尊重作者,请转明来处:追Dream梦http://blog.****.net/pzhsunxu/article/details/7798289