user8469759 user8469759 - 1 month ago 8
C Question

Pattern Rule and VPATH, makefile

Trying to practice a bit because I need to write a makefile later.
I have the followings Folder structures

./Folder1/header1.h
./Folder1/src1.c
./Folder2/header2.h
./Folder2/src2.c
main.c
Makefile


The code of each file is the following

header1.h

#include <stdio.h>

void print_1();


header2.h

#include <stdio.h>

void print_1();


src1.c

#include <header1.h>

void print_1() {
printf("This is function1\n");
}


src2.c

#include <header2.h>

void print_2() {
printf("This is function2\n");
}


main.c

#include <header1.h>
#include <header2.h>

int main(int argc, char **argv) {
print_1();
print_2();
return 0;
}


Makefile

CC=gcc
VPATH=./Folder1:./Folder2
OUT_FILE=test

%.o : %.c
$(CC) -c $< -o $@

all : %.o


The idea would have been, for the moment, let generate object files using the VPATH variable. The rule
%.o : %.c
should tell, for each source file generate the object file (they should returned in the same level of the Makefile and main.c).

The second rule should has a prerequisite the object files, so it should call the first rule.

However it doesn't work, why?

(it's been a while since my last makefile).

Answer

You can't have all depend on %.o -- percents are for pattern rules, and all is not a pattern rule. You want something like this:

CC=gcc
DIRS=Folder1 Folder2
CFILES=$(foreach dir,$(DIRS),$(wildcard $(dir)/*.c))
OFILES=$(CFILES:.c=.o)

%.o : %.c
    $(CC) -c $< -o $@

all : $(OFILES)

CFILES will contain the c files in the directories, OFILES will be a list of .o files to generate. The pattern rule will be smart enough to fill in the directory names.

Comments