Using lists as pattern rules in a Makefile

Programming, for all ages and all languages.
Post Reply
solano
Posts: 8
Joined: Mon Oct 01, 2012 12:29 pm
Location: Brazil

Using lists as pattern rules in a Makefile

Post 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?
Caspian Project developer
Brazilian OSDev'er. Sorry for the terrible English!
User avatar
qw
Member
Member
Posts: 792
Joined: Mon Jan 26, 2009 2:48 am

Re: Using lists as pattern rules in a Makefile

Post 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 $@ $<
Last edited by qw on Tue Oct 16, 2012 11:57 am, edited 1 time in total.
solano
Posts: 8
Joined: Mon Oct 01, 2012 12:29 pm
Location: Brazil

Re: Using lists as pattern rules in a Makefile

Post 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)
Caspian Project developer
Brazilian OSDev'er. Sorry for the terrible English!
User avatar
qw
Member
Member
Posts: 792
Joined: Mon Jan 26, 2009 2:48 am

Re: Using lists as pattern rules in a Makefile

Post by qw »

You're welcome. It is explained pretty clear in section 10.5.4: How Patterns Match.
Post Reply