Compile all CPP files using the make file under MinGW

The directory structure of my C ++ project is -

/.. makefile <- the makefile is in root /include <- subdirectory that has to be included while compiling /obj <- target place for all *.o and final executable /src <- sources 

And my current makefile:

 CC=g++ CFLAGS=-c -Wall -std=c++11 INC=-Iinclude SRC=src TGT=obj all: myapp myapp: myapp.o $(CC) $(TGT)/myapp.o -o $(TGT)/myapp myapp.o: $(CC) $(CFLAGS) $(INC) $(SRC)/myapp.cpp -o $(TGT)/myapp.o clean: rm -rf $(TGT) mkdir $(TGT) 

This worked for my first file. I am a complete makefile newbie, please help me compile all the files in the /src directory and link them to the executable in the /obj directory.

makefile should work under Windows, I use MinGW and MSYS

+7
source share
2 answers

Add a list of source files:

 SOURCES = $(wildcard $(SRC)/*.cpp) 

and a list of related object files:

 OBJS = $(addprefix $(TGT)/, $(notdir $(SOURCES:.cpp=.o))) 

and target executable:

 $(TGT)/myapp: $(OBJS) $(CXX) $(LDFLAGS) $(OBJS) -o $@ 

The rule for building objects:

 $(TGT)/%.o: $(SRC)/%.cpp $(CXX) $(CXXFLAGS) -c $< -o $@ 

Now you must specify the g ++ options:

 INCLUDES = -Iinclude CXXFLAGS = -Wall -std=c++11 $(INCLUDES) 

And all together:

 SRC=src TGT=obj INCLUDES = -Iinclude CXXFLAGS = -Wall -std=c++11 $(INCLUDES) SOURCES = $(wildcard $(SRC)/*.cpp) OBJS = $(addprefix $(TGT)/, $(notdir $(SOURCES:.cpp=.o))) $(TGT)/%.o: $(SRC)/%.cpp $(CXX) $(CXXFLAGS) -c $< -o $@ $(TGT)/myapp: $(OBJS) $(CXX) $(LDFLAGS) $(OBJS) -o $@ 

It is important that before the $(CXX) ... should be a "tab" character, not spaces.

+5
source

You can use VPATH to separate source and object files :

 src/myapp.c obj/Makefile 

Take the existing Makefile , move it to obj/ , omit the links to $(TGT) and $(SRC) and add the following:

 VPATH=../src 

Please note that if you are trying to do multi-archive builds, VPATH not ideal .


By the way, you do not use the built-in rules . Where are you

 CC=g++ CFLAGS=-c -Wall -std=c++11 myapp: myapp.o $(CC) $(TGT)/myapp.o -o $(TGT)/myapp myapp.o: $(CC) $(CFLAGS) $(INC) $(SRC)/myapp.cpp -o $(TGT)/myapp.o 

instead you can use:

 CXXFLAGS=-Wall -std=c++11 CXXFLAGS+=$(INC) LDLIBS+=-lstdc++ myapp: myapp.o 

So, to summarize, your new obj/Makefile should look like this:

 VPATH=../src INC=-I../include CXXFLAGS=-Wall -std=c++11 CXXFLAGS+=$(INC) LDLIBS+=-lstdc++ myapp: myapp.o 

You can create another Makefile up from obj/ to reload this new one if necessary:

 all: obj/myapp obj/myapp: mklink obj/Makefile ../Makefile $(MAKE) --directory=obj/ 
+1
source

All Articles