1

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.

1
  • Your makefile can have as many targets as is needed, so just create a target for each Exercise_4.(whatever). If you instead want a more elegant solution, you'll need to research make in more depth rather than posting here - but once you've researched enough to make an honest attempt, if it doesn't work feel free to post a question including what you've tried and how it fails to meet your requirements. Commented Dec 1, 2015 at 15:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.