kablondino
kablondino

Reputation: 25

Single make file for multiple main.cpp files

I have a project in which multiple situations need to be calculated, all using the same headers and dependencies. The directory hierarchy is as such.

/src/Chapter_4/Exercise_4.7.cpp
/src/Chapter_4/Exercise_4.9.cpp
/src/Chapter_4/Exercise_4.12.cpp (etc...)
/src/Chapter_4/Makefile

/src/header1.h
/src/header2.h (etc...)

I want to have the single Makefile that lets me run the command "make Exercise_4.(whatever)" and compiles that particular Exercise file. I really don't want to edit the Makefile every time I want to compile a different Exercise.

Keep in mind that I am very, very new to using make files.

Upvotes: 1

Views: 363

Answers (2)

Chnossos
Chnossos

Reputation: 10496

Depending of your dependencies (or lack thereof), you don't even need to write a Makefile at all. Simply doing:

$ cd /src/Chapter_4
$ make Exercice_4.x

... with x matching the one of the file you want to compile is enough because Make has a lot of implicit rules that are built-in, and it has one to compile an executable from a source file of the same name.

You can see it by doing:

$ make -p | grep -C2 "%.cpp"

... output is:

%: %.cpp
#  recipe to execute (built-in):
    $(LINK.cpp) $^ $(LOADLIBES) $(LDLIBS) -o $@

Using similar commands, we see that $(LINK.cpp) expands to $(LINK.cc) which expands to $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH).

So when you call make Exercice_4.19, it will execute something like:

g++     Exercice_4.19.cpp   -o Exercice_4.19

If you want to, let's say, add flags for warning or use a certain standard version, you can simply add the flag on the fly:

$ make Exercice_4.19 CXXFLAGS="-std=c++11 -Wall"
g++ -std=c++11 -Wall    Exercice_4.19.cpp   -o Exercice_4.19

Or write it in your Makefile:

CXXFLAGS := -std=c++11 -Wall

And then call it like before:

$ make Exercice_4.19
g++ -std=c++11 -Wall    Exercice_4.19.cpp   -o Exercice_4.19

You don't need to bother with writing rules at all for such a simple task.

Upvotes: 0

Rolf Lussi
Rolf Lussi

Reputation: 615

Something like this would work I think

%: %.cpp
    g++ $< -I../ -o $@

The rule name is same as the cpp file. So if you want to compile Excercise_4.cpp just use make Excercise_4. $< refers to your input arguments, $@ to the target name.

Upvotes: 1

Related Questions