Check gcc minor in cmake
Asked Answered
H

4

35

Is it possible to check the minor version number of GCC in cmake?

I want to do something like this:

If (GCC_MAJOR >= 4 && GCC_MINOR >= 3)
Hans answered 30/10, 2010 at 11:52 Comment(2)
possible duplicate of How can I add a minimum compiler version requisite?Veljkov
If I am guessing your intentions correctly, this will mis-detect GCC 5.0, 5.1, 6.0, 6.1, etc.Chime
V
41

Use if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.2) as mentioned by onqtam. This obsolete answer was back from the 2.6 CMake days.

You could run gcc -dumpversion and parse the output. Here is one way to do that:

if (CMAKE_COMPILER_IS_GNUCC)
    execute_process(COMMAND ${CMAKE_C_COMPILER} -dumpversion
                    OUTPUT_VARIABLE GCC_VERSION)
    string(REGEX MATCHALL "[0-9]+" GCC_VERSION_COMPONENTS ${GCC_VERSION})
    list(GET GCC_VERSION_COMPONENTS 0 GCC_MAJOR)
    list(GET GCC_VERSION_COMPONENTS 1 GCC_MINOR)

    message(STATUS ${GCC_MAJOR})
    message(STATUS ${GCC_MINOR})
endif()

That would print "4" and "3" for gcc version 4.3.1. However you can use CMake's version checking syntax to make life a bit easier and skip the regex stuff:

execute_process(COMMAND ${CMAKE_C_COMPILER} -dumpversion
                OUTPUT_VARIABLE GCC_VERSION)
if (GCC_VERSION VERSION_GREATER 4.3 OR GCC_VERSION VERSION_EQUAL 4.3)
        message(STATUS "Version >= 4.3")
endif()

Vagarious answered 31/10, 2010 at 23:34 Comment(3)
I found that really useful, thanks. Is there a way to strip the newline from version number ?Hetti
As of gcc 7, -dumpversion now outputs simply 7, so this is broken. Prefer the answer by onqtam which is far more portable.Fafnir
2.8.10 has now the variable, but you may want to known that gcc has -dumpfullversionCahoot
I
27

Combining the 2 other answers, you can check the specific gcc version as follows:

if (CMAKE_COMPILER_IS_GNUCC AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 5.1)
    ...
endif()
Implicatory answered 23/8, 2016 at 21:28 Comment(0)
A
25

Since CMake 2.8.10 there are the CMAKE_C_COMPILER_VERSION and CMAKE_CXX_COMPILER_VERSION variables exactly for this purpose so you can do this:

if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.2)
Auricular answered 25/2, 2016 at 1:44 Comment(1)
This should be the accepted answer: shorter, simpler, well-defined for all current and future compiler versions. The answer accepted right now (by richq) has a problem: -dumpversion now returns 7 in gcc 7, so it's a broken solution.Fafnir
S
1

However, there is an argument, -dumpfullversion that provides the full version string.

gcc -dumpfullversion

should get what you want. Still backward compatibility is broken in gcc 7.

Sender answered 7/5, 2018 at 17:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.