您的位置:首页 > 其它

makefile 中 $@ $^ %< ar rz使用

2016-02-23 13:18 246 查看

1.源程序的编译

假设我们有如下程序

/* main*/

#include <stdio.h>
#include "test1.h"
#include "test2.h"
void main()
{
test1();
test2();
printf("main\n");
}


/*test1*/
#include <stdio.h>
void test1()
{
printf("test1\n");
}
/*test2*/
#include <stdio.h>
void test1()
{
printf("test1\n");
}


程序可以这么编译:

gcc -c test1.c

gcc -c test2.c

gcc -c main.c

gcc -o test main.o test1.o test2.o

如果有上百个源程序,编译就比较麻烦,为此发明了makefile.

2.Makefile

test: main.o test1.o test2.o

gcc -o test main.o test1.o test2.o

main.o: main.c test1.c test2.c

gcc -c main.c

test1.o: test1.c test1.h

gcc -c test1.c

test2.o: test2.c test2.h

gcc -c test2.c


Makefile有三个非常有用的变量。分别是$@,$^,$<代表的意义分别是:

$@–目标文件,$^–所有的依赖文件,$<–第一个依赖文件。

如果我们使用上面三个变量,那么我们可以简化我们的Makefile文件为:

test: main.o test1.o test2.o

gcc -o $@ $^

main.o: main.c test1.c test2.c

gcc -c $<

test1.o: test1.c test1.h

gcc -c $<

test2.o: test2.c test2.h

gcc -c $<


也可以最终简化为这样:

test: main.o test1.o test2.o

gcc -o $@ $^

.c.o:

gcc -c $<


这个规则表示所有的 .o文件都是依赖与相应的.c文件的。

AR = ar rc —–生成静态库文件命令

test.a: test1.o test2.o
ar rc test.a test1.o test2.o
test: main.o test1.o test2.o
gcc -o $@ $^
.c.o:
gcc -c $<
clean:
rm -fr *.o *.a
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  makefile