juztcode
juztcode

Reputation: 1355

applying the DRY principles in makefile

Just taking a use case for this instance. I'm compiling a c++ file, and sometimes, I'd like to compile without debugging symbols i.e. the -g enabled and sometimes I would like to enable it.

So, I thought of just making two targets in which the second target would reassign a make variable(is it possible) and change the compiling options. I wonder if such a behaviour is possible to achieve with makefiles?

Below is some pseudocode demo and the user enters make first@bg into the command line:

gpp = g++ -std=c++17

first: hello.cpp
    $(gpp) hello.cpp -o $@
    #/* some other recipes, assuming the list is really long*/

first@bg: main.o
    gpp = g++ -g -std=c++17 
    execute_all_recipe_of_first_target_which_is_really_long_to_copy()  

main.o: main.cpp
    $(gpp) main.cpp -c -o main.o #the value of gpp should'd also changed here since first@bg executed

If it is possible please provide me with the actual syntax for the demonstrated behaviour. Thanks in advance.

Upvotes: 0

Views: 121

Answers (1)

cdhowie
cdhowie

Reputation: 169183

You can do something like this:

first@bg: gpp += -g
first@bg: first

Note that it's more idiomatic to define CXX=g++ and CXXFLAGS=-std=c++17 and then tweak CXXFLAGS, and use make DEBUG=1 for debug builds:

CXX=g++
CXXFLAGS=-std=c++17
ifeq ($(DEBUG), 1)
  CXXFLAGS+=-g
endif

Then invoke the compiler as $(CXX) $(CXXFLAGS) hello.cpp -o $@ for example. See also this link

Upvotes: 2

Related Questions