Daniel Koch
Daniel Koch

Reputation: 610

Can I conditionally define a macro in Makefile in a portable way?

I've been struggling to define a macro named DEBUG conditionally in a portable Makefile when the target-name is debug.

.POSIX:
.SUFFIXES:

CFLAGS = -Wall -O3 $(DEBUG)

all: hello
debug: DEBUG=-O0 -g
debug: all
hello: main.o
    $(CC) $(LDFLAGS) -o hello main.o $(LDLIBS)
main.o: main.c
    $(CC) $(CFLAGS) -c main.c

It works fine on GNU Make but I can't run it on bmake or fmake (from Debian's freebsd-buildutils).

$ fmake debug
make: don't know how to make DEBUG=-O0. Stop

According to an ancient SunOS Make User's Guide, there was a special syntax to Conditional Macro Definitions, but it just doesn't work:

target-name := macro = value 

Also, I haven't found a standard way in the make's official specification.

How can I define DEBUG conditionally in a portable fashion?

Upvotes: 1

Views: 61

Answers (1)

MadScientist
MadScientist

Reputation: 100966

The only way to do it portably is via recursion:

debug:
        $(MAKE) all DEBUG='-O0 -g'

Any POSIX-compliant version of make will handle this properly.

Upvotes: 2

Related Questions