Page 1 of 1

Using lists as pattern rules in a Makefile

Posted: Tue Oct 16, 2012 9:55 am
by solano
I want my OS's source code to be in the directory src and to be built into build/obj and build/bin. So I started writing the Makefile:

Code: Select all

CC	= i586-elf-gcc
CFLAGS	= -Wall -Wextra -nostdlib -fno-builtin -nostartfiles -nodefaultlibs
LD	= i586-elf-ld
ASM = nasm
ASMFLAGS = -f elf

SRCDIRS = src #no subdirectory for now
SRC_C := $(wildcard $(addsuffix *.c, $(SRCDIRS))) #c
SRC_S := $(wildcard $(addsuffix *.s, $(SRCDIRS))) #asm
SRCFILES = $(SRC_C) $(SRC_S)
HEADERS := $(wildcard $(addsuffix *.h, $(SRCDIRS)))

OBJDIR = build/obj
OBJ_C := $(addprefix $(OBJDIR)/, $(addsuffix .o, $(notdir $(SRC_C))))
OBJ_S := $(addprefix $(OBJDIR)/, $(addsuffix .o, $(notdir $(SRC_S))))
OBJFILES = $(OBJ_C) $(OBJ_S)

BUILD_DIR = build/bin
Then I have to write the rules. I wanna make them like this:

Code: Select all

$(OBJ_C): $(SRC_C)
	compile command here, as a foreach
And that doesn't work. I can use eval with foreach to write it as a pattern rule (%.o: %.c) for each source directory (right now src has no subdirectories, but it will). However, that seems a bit ugly for me. Is there a cleaner way?

Re: Using lists as pattern rules in a Makefile

Posted: Tue Oct 16, 2012 11:48 am
by qw
This should do:

Code: Select all

$(objdir)/%.o : $(srcdir)/%.c
	 $(CC) $(ETCETERA) -o $@ $<
This will work if the subdirectories match, that is if $(objdir)/foo/bar.o must be built from $(srcdir)/foo/bar.c. Otherwise, VPATH may help you:

Code: Select all

VPATH = list:of:directories:to:search:for:dependencies

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

Re: Using lists as pattern rules in a Makefile

Posted: Tue Oct 16, 2012 11:59 am
by solano
Thank you very much, Hobbes :)

I noted only now that $(srcdir)%.c will match with subdirectories too. VPATH will also help.

(actually I read make's documentation, but didn't fully understand. Must improve my English skills)

Re: Using lists as pattern rules in a Makefile

Posted: Tue Oct 16, 2012 12:13 pm
by qw
You're welcome. It is explained pretty clear in section 10.5.4: How Patterns Match.