Abdullah
Abdullah

Reputation: 541

Including multiple sub directories in a make file

I am trying to write a makefile for a small scale application I wrote in C under Linux. Currently all my source files .c are in the top level directory and all header files in an include directory. Here is the makefile I used for this.

IDIR =include
CC=gcc
CFLAGS=-I$(IDIR)


ODIR=obj

_OBJ = main.o kernel.o user_app.o myargs.o ofp_msgs.o pkt_ip.o pkt_ether.o pkt_tcp.o pkt_udp.o pkt_icmp.o 
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ))

#DEPS = ofp_msgs.h




$(ODIR)/%.o: %.c 
    $(CC) -c -o $@ $< $(CFLAGS)            
all: jam

jam: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)  -lpthread

.PHONY: clean

clean:
    rm -f $(ODIR)/*.o *~ jam 

It works fine but what I want is that for example I make a sub directory called "Packet" and all my packet parsing files i-e "pkt_ip.c, pkt_tcp.c etc" should be in that directory where as their header files should still be in the top level directory i-t "toplevel/include". I did a bit of search and the most common way was to use recursive make. Then I see a lots of pages complaining about recursive make. Can anyone please help me in this as how to do this right ? Thanks

Upvotes: 2

Views: 10825

Answers (2)

Kristian
Kristian

Reputation: 486

I recommend checking out the method described in Recursive Make Considered Harmful. I have used it on several projects (small to medium-size), and find it simpler to use, and easier to wrap ones head around, than the recursive approach.

Basically, you have a Makefile in the root directory which includes a (partial) makefile from each of the subdirectories:

SRC := main.c
MODULES := Packet lib etc
-include $(patsubst %, %/module.mk, $(MODULES))

OBJ := $(patsubst %.c, %.o, $(filter %.c,$(SRC)))
# (...)

Packet/module.mk:

SRC += Packet/pkt_ip.c Packet/pkt_tcp.c
LIBS += -lsome_library

These module makefiles can of course also define their own module targets, or special build requirements.

Unlike recursive make, "make" will only be invoked once, which for most use cases will lead to a faster build. However, for most smaller projects neither build time nor complexity will be a major concern, so use what feels most natural.

Upvotes: 3

mbonnin
mbonnin

Reputation: 7032

there are several ways to do this but you can certainly use VPATH:=Packet to tell make to look for source files inside the 'Packet' directory. see make manual

Upvotes: 3

Related Questions