Patrick Jane
Patrick Jane

Reputation: 336

Makefiles output directory

I am a bit a beginner in using makefiles and I am trying to write a makefile for gcc that accepts the inputs from two different directories (in my case they are called kernel and drivers) and output the object files in a different directory (called tmp) using wildcards.

I have written this code to get the names of input files and output files

C_SOURCES = $(wildcard $(KERNEL_DIR)/*.c $(DRIVERS_DIR)/*.c)

#Creating a list for object files names
C_OBJ = $(C_SOURCES:.c=.o)

and I am using the following rule

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

but i can't get to output the object files in the desired directory.files

Upvotes: 1

Views: 6578

Answers (2)

MadScientist
MadScientist

Reputation: 101131

You have to make a separate rule for each subdirectory, like this:

SOURCES := $(wildcard $(KERNEL_DIR)/*.c $(DRIVER_DIR)/*.c)
OBJECTS := $(patsubst %.c,$(OBJECT_DIR)/%.o,$(notdir $(SOURCES)))

all: $(OBJECTS)

$(OBJECT_DIR)/%.o : $(KERNEL_DIR)/%.c
        $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

$(OBJECT_DIR)/%.o : $(DRIVER_DIR)/%.c
        $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

Obviously you'll have big problems if you have a foo.c file in both source directories...

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225262

Something like this example should do it for you. I split things up a bit for readability, but I'm sure you'll get the idea:

KERNEL_SOURCES = $(wildcard $(KERNEL_DIR)/*.c)
DRIVER_SOURCES = $(wildcard $(DRIVER_DIR)/*.c)

OBJECTS =  $(patsubst $(KERNEL_DIR)/%.c,tmp/%.o,$(KERNEL_SOURCES))
OBJECTS += $(patsubst $(DRIVER_DIR)/%.c,tmp/%.o,$(DRIVER_SOURCES))

Watch out for source files with the same name in both KERNEL_DIR and DRIVER_DIR!

Upvotes: 2

Related Questions