1、VPATH为了解决什么样的问题?
如下这个文件结构我们使用make工程管理工具来进行编译工作,怎么样写一个对应的makefile
默认情况下,make时只会在当前目录下(也就是VPATH目录)寻找目标和依赖,也就是寻找main.o main.c这类文件,但是当前目录没有这些文件,肯定不能生成最终的目标文件interface,那么如何在其它目录下搜索目标和依赖呢? 对于这个情况在Makefile中可以使用VPATH或者vpath告诉make所需要的源文件路径。
2、实列分析
其中每一个文件中的代码如下:
/********************src/add.c********************/
#include <stdio.h>
int add(int value1,int value2)
{
return value1 + value2;
}
/******************src/sub.c***********************/
#include <stdio.h>
int sub(int value1,int value2)
{
return value1 - value2;
}
/***************src/main.c*********************/
#include <stdio.h>
#include "sub.h"
#include "add.h"
int main(int argc, const char *argv[])
{
int a=8,b=4,temp;
printf("this is main.c\n");
printf("this is add.c:value1 + value2= %d\n",add(a,b));
printf("this is sub.c:value1 - value2 = %d\n",sub(a,b));
return 0;
}
/***************include/add.h****************/
#ifndef __ADD_H__
#define __ADD_H__
extern int add(int ,int );
#endif
/*************include/sub.h****************/
#ifndef __SUB_H__
#define __SUB_H__
extern int sub(int , int);
#endif
但是VAPTH只对make起作用,以便make找到目标和依赖,不会对编译起任何作用。而工程文件中有一个目录include存放了各种头文件,在编译器编译代码的时候必须要有,所以需要加一个-I告诉编译器需要的头文件的位置
/***************Makefile********************/
CC =gcc
OBJ =main.o add.o sub.o
CFLAGS = -I include
VPATH =src:include
interface:$(OBJ)
$(CC) -o $@ $(OBJ)
%.o:%.c
$(CC) $(CFLAGS) -c $<
.PHONY:clean
clean:
rm -rf $(OBJ) interface