barej
barej

Reputation: 1406

My desired automatic make file

I am new in make file.

I have a program made of

main.cpp
types.hpp
application/coordinator.hpp
application/correlation.hpp
application/handler.hpp
application/settings.hpp
libraries/basket.hpp
libraries/config.hpp
libraries/graphics.hpp
...

I have so many files and the list of my files will be updated so many times. I want the make file recognizes automatically which .o file to be generated or updated. I don't want to update my make file each time I create and include a new file. The output must be generated in a directory called bin

main.cpp is my only cpp file and the rest of my files are hpp.

Till now, this link has inspired me to write this code:

CC=g++
CFLAGS= -g -Wfatal-errors 

CFLAGS+= -std=c++11
LIBS= -lboost_filesystem -lboost_system

all: run

run: $(OBJS)
    $(CC) $(CFLAGS) $^ main.cpp -o $@

$(OBJS): bin/%.o : bin/%.hpp

How to improve it to working code and what I want?

Upvotes: 1

Views: 1424

Answers (2)

Bulletmagnet
Bulletmagnet

Reputation: 6010

Here's a different scheme: generate the dependency information while you build the software. This works with multiple cpp files creating multiple object files.

CXX := g++
#CPPFLAGS := preprocessor flags, e.g. -I and -D
CXXFLAGS := -g -Wall -pedantic -Wextra -Wfatal-errors -std=c++11 -MD -MP

SOURCES := main.cpp
OBJECTS := $(SOURCES:.cpp=.o)
DEPFILES:= $(OBJECTS:.o=.d)

all: run

# Link the executable
run: $(OBJECTS)
    $(CXX) $(LDFLAGS) $^ -o $@ $(LIBS)

-include $(DEPFILES)

When .o files are built, the -MD -MP flags tell the compiler to generate the dependency file as a side-effect. These dependency files are included into the makefile if they are present.

This uses GNU make's built-in %.o : %.cpp rule. We just supply parameters to it (CXX, CPPFLAGS, CXXFLAGS).

Make already knows to rebuild .o files if the corresponding .cpp file is newer (either GNU make's built-in rule or a hand-written one). With .d files included into the makefile, we tell make that the object file also depends on the header files and should be rebuilt when one of them changes. But the rule to rebuild the .o is always %.o : %.cpp

Upvotes: 3

Bulletmagnet
Bulletmagnet

Reputation: 6010

If you intend to only ever have one cpp file, you could write the makefile in the following way:

CXX := g++
CXXFLAGS := -g -Wall -pedantic -Wextra

HEADERS := types.hpp $(wildcard application/*.hpp) $(wildcard libraries/*.hpp)

all: run

run: main.cpp $(HEADERS)
    $(CXX) $(CXXFLAGS) $< -o $@

$(wildcard) will find all headers in application and libraries. The executable will depend on all the headers and main.cpp so if any of them changes, the binary will be rebuilt.

$< means "first dependency". This way, only the cpp file is passed to the compiler.

Note: in GNU make conventions, CC and CFLAGS refer to the C compiler. For C++, the variables are named CXX and CXXFLAGS.

Upvotes: 4

Related Questions