Josh Weinstein Josh Weinstein - 3 years ago 205
C++ Question

How to compile all cpp files in multiple sub directories?

So currently, I have a makefile setup where I compile all the cpp files in a single directory,

src
. It is structured as follows

CCPP = g++
CPPFLAGS = -std=c++11
CPPLINK = -lstdc++
INC_DIR = include

CPP_FILES := $(wildcard src/*.cpp)
OBJ_FILES := $(addprefix lib/,$(notdir $(CPP_FILES:.cpp=.o)))
LD_FLAGS :=
CC_FLAGS := -c $(CPPFLAGS) -Wall -I$(INC_DIR)

bin/Xenon: $(OBJ_FILES) ; $(CCPP) $(LD_FLAGS) -o $@ $^

lib/%.o: src/%.cpp ; $(CCPP) $(CC_FLAGS) -c -o $@ $<


However, although this works, I want to divide src into multiple sub directories of cpp files.

How would I make this solution work for any number of sub directories under a single
src
folder?

Note: Here
bin/Xenon
is a CLI application executable with a main method, and INC_DIR is where all my header files are. This is also on OSX, not windows.

Answer Source

The easy part is

CPP_FILES := $(wildcard src/*/*.cpp)   # if all are in subdirectories
CPP_FILES := $(wildcard src/*.cpp src/*/*.cpp)
OBJ_FILES := $(patsubst src/%,lib/%,$(CPP_FILES:.cpp=.o))

You don't want $(notdir) if you might have the same file name in multiple directories.

You'll also have to worry about making the corresponding subdirectories of lib. The simplest thing to do might be to make sure each exists when writing to it:

lib/%.o: src/%.cpp
    mkdir -p $(dir $@)
    $(CCPP) $(CC_FLAGS) -c -o $@ $<
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download