makefilegnu-makevpath

Makefile: Can VPATH variable is applied to assigning Makefile variable?


i've tried to write simple makefile for practice.

I have two directories 1. srcs(.c), 2.include(.h)

and try to define SRCS variable that would contain all .c files

in current directory and srcs directory.

and below is my Makefile

CURDIR = $(shell pwd)
OBJDIR = $(CURDIR)/objdir
VPATH = $(CURDIR)/srcs
SRCS = $(wildcard *.c)
OBJS = $(patsubst %.c, %.o, $(SRCS))

all: main

main: $(OBJS)
        gcc -o $@ $^

$(OBJS): $(SRCS) | $(OBJDIR)
        gcc -c -o $@ $<

$(OBJDIR): 
        mkdir objdir

I designate current/src directory as a VPATH to make find

all *.c files in current directory and current/srcs but

it cannot find *.c files in /srcs directory.

May be make cannot us VPATH when it defines the variable in Makefile

right? if it's right please let me know better approach :)

Thanks.


Solution

  • VPATH is for directories make should search to find prerequisites.

    It doesn't change where $(wildcard) searches.

    VPATH lets you use foo.c (either explicitly or implicitly) in the prerequisite list of a rule and have make look in the current directory and the VPATH directories for the file for it.

    If you want SRCS to contain the .c files from the srcs directory then you need to include srcs/*.c in an additional $(wildcard) call in the SRCS assignment.

    SRCS = $(wildcard *.c) $(wildcard srcs/*.c)