Checking the gcc version in a Makefile?

Gene Vincent picture Gene Vincent · Mar 4, 2011 · Viewed 42.4k times · Source

I would like to use some gcc warning switchs that aren't available in older gcc versions (eg. -Wtype-limits).

Is there an easy way to check the gcc version and only add those extra options if a recent gcc is used ?

Answer

srgerg picture srgerg · Mar 4, 2011

I wouldn't say its easy, but you can use the shell function of GNU make to execute a shell command like gcc --version and then use the ifeq conditional expression to check the version number and set your CFLAGS variable appropriately.

Here's a quick example makefile:

CC = gcc
GCCVERSION = $(shell gcc --version | grep ^gcc | sed 's/^.* //g')
CFLAGS = -g

ifeq "$(GCCVERSION)" "4.4.3"
    CFLAGS += -Wtype-limits
endif

all:
        $(CC) $(CFLAGS) prog.c -o prog

Edit: There is no ifgt. However, you can use the shell expr command to do a greater than comparison. Here's an example

CC = gcc
GCCVERSIONGTEQ4 := $(shell expr `gcc -dumpversion | cut -f1 -d.` \>= 4)
CFLAGS = -g

ifeq "$(GCCVERSIONGTEQ4)" "1"
    CFLAGS += -Wtype-limits
endif

all:
        $(CC) $(CFLAGS) prog.c -o prog