nikost
nikost

Reputation: 858

Makefile change suffix rule based on target

Currently, I have two sets of flags in my Makefile. I comment one out if I want my program to be optimized or if I want more debugging information (see below).

FC = gfortran
# I switch between having one of the following two lines commented
# FFLAGS = -Og -Wall -Wextra -fcheck=all -fbacktrace -fbounds-check
FFLAGS = -O3
MOD='Modules/'

SRC  = Modules/pyplot_module.f90
SRC += Modules/logs.f90
SRC += program.f90
OBJ  = ${SRC:.f90=.o}

%.o: %.f90
    $(FC) -c -J${MOD} $< $(FFLAGS) -o $@

program: $(OBJ)
    $(FC) -J${MOD} $(FFLAGS) -o $@ $(OBJ)

remake: remove program

clean:
    rm -f **/*.o **/*.mod

remove: clean
    rm -f program

Is there a way to have two different suffix rules and have a specific one used based on which target I call. I desire something like I have show below. I suspect this is an XY problem, but I don't know how else to approach this.

FC = gfortran
# Notice changes here
DEBUGFFLAGS = -Og -Wall -Wextra -fcheck=all -fbacktrace -fbounds-check
FFLAGS = -O3
MOD='Modules/'

SRC  = Modules/pyplot_module.f90
SRC += Modules/logs.f90
SRC += program.f90
OBJ  = ${SRC:.f90=.o}

%.o: %.f90
    $(FC) -c -J${MOD} $< $(FFLAGS) -o $@

%.o: %.f90 # I want this suffix rule to be used only when program-debug target is made
    $(FC) -c -J${MOD} $< $(DEBUGFFLAGS) -o $@

program-optimized: $(OBJ)
    $(FC) -J${MOD} $(FFLAGS) -o $@ $(OBJ)

program-debug: $(OBJ)
    # But I also want the SRC files to be compiled with these flags aswell 
    $(FC) -J${MOD} $(DEBUGFFLAGS) -o $@ $(OBJ)

remake: remove program

clean:
    rm -f **/*.o **/*.mod

remove: clean
    rm -f program

Upvotes: 0

Views: 100

Answers (1)

MadScientist
MadScientist

Reputation: 100781

You can use target-specific variables to do this, like this:

DEBUGFFLAGS = -Og -Wall -Wextra -fcheck=all -fbacktrace -fbounds-check
FFLAGS = -O3

EXTRAFLAGS =

%.o: %.f90
         $(FC) -c -J${MOD} $< $(FFLAGS) $(EXTRAFLAGS) -o $@

program-optimized program-debug: $(OBJ)
         $(FC) -J${MOD} $(FFLAGS) $(EXTRAFLAGS) -o $@ $(OBJ)

program-debug: EXTRAFLAGS = $(DEBUGFLAGS)  # this is the magic

However, this is a bad idea.

The problem is make won't rebuild your object files when you change the flags, it only rebuilds when the files are edited. So, whenever you run make you could have some mix of object files compiled with optimized options and debug options, and you'll never know which are which unless you completely clean all object files in between builds.

Much better is to create a separate subdirectory to hold the object files built for debug versus optimized, then they don't conflict with each other.

Upvotes: 2

Related Questions