makefile学习2:使用变量

版权声明:欢迎转发,转发请标明出处 https://blog.csdn.net/weixin_39465823/article/details/88950733

 源代码1:

gyz@debian:~/mc$ cat test.c 
#include "std.h"

int main(int argv,char **argc)
{
	int arr[10] = {1,2,3,4,5,6,7,8,9,10};
	PrintArray(10,arr);
	return 0;
}


源代码2:

gyz@debian:~/mc$ cat printarr.c 
#include "std.h"

void PrintArray(int n,int arr[])
{
	int i = 0;
	for(;i < n;i++)
	{
		printf("%d\n",arr[i]);
	}
}

头文件:

gyz@debian:~/mc$ cat std.h 
#ifndef _STD_H
#define _STD_H

#include <stdio.h>

void PrintArray(int n,int arr[]);

#endif

makefile:

gyz@debian:~/mc$ cat Makefile 
test:test.o printarr.o
	gcc -o test test.o printarr.o
test.o:test.c std.h
	gcc -c test.c 
printarr.o:printarr.c std.h
	gcc -c printarr.c

.PHONY:clean
clean:
	rm test test.o printarr.o

执行:

gyz@debian:~/mc$ make 
gcc -c test.c 
gcc -o test test.o printarr.o
gyz@debian:~/mc$ ./test 
1
2
3
4
5
6
7
8
9
10
gyz@debian:~/mc$ make clean
rm test test.o printarr.o

解释:

从上面可以看到,xxx.c里面有哪个.h文件,makefile里面xxx.o的依赖文件除了.c外,就是对应的.h文件了。

现在只有两个.c文件,如果有很多那.o文件不是会相应的变多,写起来也繁琐,所以引入变量。所以新的makefile就变成了:

gyz@debian:~/mc$ cat Makefile 
obj=test.o printarr.o
test:$(obj)
	gcc -o test $(obj)
test.o:test.c std.h
	gcc -c test.c 
printarr.o:printarr.c std.h
	gcc -c printarr.c

.PHONY:clean
clean:
	rm test $(obj)

执行:

gyz@debian:~/mc$ make
gcc -c test.c 
gcc -o test test.o printarr.o
gyz@debian:~/mc$ ./test 
1
2
3
4
5
6
7
8
9
10
gyz@debian:~/mc$ make clean
rm test test.o printarr.o

现在看起来就没有那么麻烦了。

参考:http://www.cnblogs.com/liangxiaxu/archive/2012/07/31/2617384.html

扫描二维码关注公众号,回复: 5740829 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_39465823/article/details/88950733