views:

390

answers:

1

So, my project directory looks like this:

/project
    Makefile
    main
    /src
        main.cpp
        foo.cpp
        foo.h
        bar.cpp
        bar.h
    /obj
        main.o
        foo.o
        bar.o

What I would like my makefile to do would be to compile all .cpp files in the /src folder to .o files in the /obj folder, then link all the .o files in /obj into the output binary in the root folder /project.

The problem is, 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?

+1  A: 

So, the 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 $@ $<

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

bobah
Ah, you beat me by seconds. But I suggest `OBJ_FILES = $(patsubst src/%.cpp,obj/%.o,$(CPP_FILES))`.
Beta