Search code examples
c++c++11gccc++14gnu-make

Can I have my Makefile automatically make GCC use the most recent standard it supports?


My C++03 project needs an upgrade to C++11, and I can guarantee that at least experimental support for it will be available in all the GCCs I want to use.

However, that may be -std=c++0x or it may be actual -std=c++11 from newer GCC. One day it'll be -std=c++14 (when CentOS catches up…).

How can I form a GNU Makefile that adds the "best" flag to CXXFLAGS depending on which will succeed?

I could just say "okay, my earliest GCC in use still doesn't have production-ready C++11 support so I should stick with C++03", but meh.


Solution

  • This will select the best option supported by the $(CXX) compiler:

    CXX_MODE.42 := -std=c++98
    CXX_MODE.43 := $(CXX_MODE.42)
    CXX_MODE.44 := $(CXX_MODE.43)
    CXX_MODE.45 := $(CXX_MODE.44)
    CXX_MODE.46 := -std=c++0x
    # Unnecessary, since -std=c++0x still works, but hey why not:
    CXX_MODE.47 := -std=c++11
    CXX_MODE.48 := $(CXX_MODE.47)
    CXX_MODE.49 := $(CXX_MODE.48)
    CXX_MODE.5 := -std=c++14
    CXX_MODE.6 := $(CXX_MODE.5)
    GXX_VERSION := $(shell $(CXX) -dumpversion | awk -F. '$$1<5{print $$1$$2} $$1>=5{print $$1}')
    CXX_MODE := $(CXX_MODE.$(GXX_VERSION))
    CXXFLAGS += $(CXX_MODE)
    

    For extra fun you could choose between c++ and gnu++ modes based on some other variable:

    CXX_MODE.42 := 98
    CXX_MODE.43 := $(CXX_MODE.42)
    CXX_MODE.44 := $(CXX_MODE.43)
    CXX_MODE.45 := $(CXX_MODE.44)
    CXX_MODE.46 := 0x
    # Unnecessary, since -std=c++0x still works, but hey why not:
    CXX_MODE.47 := 11
    CXX_MODE.48 := $(CXX_MODE.47)
    CXX_MODE.49 := $(CXX_MODE.48)
    CXX_MODE.5 := 14
    CXX_MODE.6 := $(CXX_MODE.5)
    GXX_VERSION := $(shell $(CXX) -dumpversion | awk -F. '$$1<5{print $$1$$2} $$1>=5{print $$1}')
    CXX_MODE := $(CXX_MODE.$(GXX_VERSION))
    ifneq($(STRICT),)
    CXXFLAGS += -std=c++$(CXX_MODE) -pedantic -pedantic-errors
    else
    CXXFLAGS += -std=gnu++$(CXX_MODE)
    endif