views:

243

answers:

4

In my C++ project, I have a convention where whenever the macro DEBUG is defined, debugging printf-esque statements are compiled into the executable.

To indicate whether or not I want these compiled into the executable, I normally would pass the macro name to gcc with the -Dmacro option. So, in the Makefile I (currently) have:

CXXFLAGS += -g -I ../ -Wall -Werror -DDEBUG

However, this is not very flexible; if I didn't want debug statements in my final program, I'd have to modify the Makefile to remove the -DDEBUG.

Is there a way to modify the Makefile such that I can conditionally select whether to compile with -D in the CXXFLAGS at compile time by passing in, say, another target name or a commandline switch? Not sure how'd I go about doing that.

+2  A: 

Append another variable that you can set from the CLI or environment

$ cat Makefile
CXXFLAGS += $(CLIFLAGS)

maintarget:
    echo $(CXXFLAGS)
$ make CLIFLAGS=-DDEBUG
echo -DDEBUG
-DDEBUG
$
DigitalRoss
+3  A: 

You can conditionally define other variables based on the target in the makefile.

all:    target
debug:  target

debug:  DEBUG=PLOP

target:
        @echo "HI $(DEBUG)"

So now:

> make
HI
>
> make debug
HI PLOP
>
Martin York
Nice and simple.
sheepsimulator
+1  A: 

Consider this one: http://users.softlab.ece.ntua.gr/~ttsiod/makefile.html

Amro
A: 

After meditating upon the make documentation, I tried putting this in my Makefile:

ifneq(,$(findstring d,$(MAKEFLAGS)))
CXXFLAGS += <... all normal options ...> -DDEBUG
else
CXXFLAGS += <... all normal options ...>
endif

Then, when you run make -d, -DDEBUG is set.

Now, mind you, it works, but I had to use a normal flag that make usually accepts (you can't make up your own). Using -d also spews (harmless) verbose make-level debugging statements to the screen. Which I really don't want; it obscures compile errors. But it does work.

I hope someone can come up with a better idea.

sheepsimulator
Amro's link has a variation on this idea, which is better than mine.
sheepsimulator