Austin Hyde Austin Hyde - 1 year ago 71
C++ Question

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

My project directory looks like this:


What I would like my makefile to do would be to compile all
files in the
folder to
files in the
folder, then link all the
files in
into the output binary in the top-level folder

I have next to no experience with Makefiles, and am not really sure what to search for to accomplish this.

Also, is this a "good" way to do this, or is there a more standard approach to what I'm trying to do?

Answer Source

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

CPP_FILES := $(wildcard src/*.cpp)
OBJ_FILES := $(addprefix obj/,$(notdir $(CPP_FILES:.cpp=.o)))
LD_FLAGS := ...
CC_FLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LD_FLAGS) -o $@ $^

obj/%.o: src/%.cpp
   g++ $(CC_FLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CC_FLAGS and -include $(OBJFILES:.o=.d) to the end of the makefile body:

-include $(OBJFILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download