问题
I started a simple makefile for my project (MS-windows target, MinGW) with the following :
CFLAGS = -g -O0 -Wall -std=c99
CC = gcc
CPP = g++
LIBS =
PBDUMPER = pbdumper.exe
all: $(PBDUMPER)
$(PBDUMPER): pbdumper.c
$(CC) $(CFLAGS) -o $@ $< $(LIBS)
clean:
rm -f $(PBDUMPER)
.PHONY: clean
Now I would like to choose between release and debug compilation. I have changed the variable definitions and implicit rule for debug :
CFLAGS_COMMON = -std=c99
CFLAGS_DEBUG = -g -O0 -Wall
CFLAGS_RELEASE = -O2 -Wall
...
$(PBDUMPER): pbdumper.c
$(CC) $(CFLAGS_COMMON) $(CFLAGS_DEBUG) -o $@ $< $(LIBS)
But for release I would have to change the implicit rule to use the CFLAGS_RELEASE which is I suppose the wrong way to do. I have looked at the Gnu Make manual in the "implicit rules" and "automatic variables" sections but I did not found a better way.
Could you show me the correct way, by either conditionally defining the CFLAGS, or maybe using a "if" in the implicit rules based on the flavour selected for compilation ? Or maybe another method.
回答1:
For the sake of archiving the solution and not keeping a question unanswered, here is the final word : following Maxim's suggestion, I have reworked my Makefile as :
#debug is default, for another flavor : make BUILD=release
BUILD := debug
cflags.common := -std=c99
cflags.debug := -g -O0 -Wall
cflags.release := -O2 -Wall
CFLAGS := ${cflags.${BUILD}} ${cflags.common}
LIBS =
CC = gcc
CPP = g++
#executable
PBDUMPER = pbdumper.exe
all: $(PBDUMPER)
$(PBDUMPER): pbdumper.c
$(CC) $(CFLAGS) -o $@ $< $(LIBS)
clean:
rm -f $(PBDUMPER)
.PHONY: clean all
回答2:
The easiest way would be a simple comment/uncomment solution:
CFLAGS = -std=c99
# Release
# CFLAGS += -O2 -Wall
# Debug
CFLAGS += -g -O0 -Wall
This is how automake does this type of configuration. You could also use a make conditional around these lines:
ifeq ($(build),release)
CFLAGS += -O2 -Wall
else
CFLAGS += -g -O0 -Wall
endif
In general, be careful with such schemes because you absolutely have to clean out old object files on release. Two-tree builds with autoconf and automake (or a simple hand-rolled configure) are more reliable, even though a little harder to set up.
来源:https://stackoverflow.com/questions/8035394/gnu-make-how-to-make-conditional-cflags