Conditionally select compiler based on its version - c++

Goals
Make cmake select clang++ if its version is above 10; otherwise, use g++. If clang++ is below 10 and the default g++ is below 10.1, use g++-10 (REQUIRED).
This is to achieve compiler fallback.
Background
As kindly noted in this answer, one should set the default compiler before the project keyword.
Instead of using
-DCMAKE_CXX_COMPILER=clang++
or
set(CMAKE_CXX_COMPILER clang++)
I used the following statements with reference to the answer here:
find_program(CMAKE_CXX_COMPILER
NAMES $ENV{CXX} clang++ PATHS ENV PATH NO_DEFAULT_PATH)
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10)
find_program(CMAKE_CXX_COMPILER
NAMES $ENV{CXX} g++ PATHS ENV PATH NO_DEFAULT_PATH)
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10.1)
find_program(CMAKE_CXX_COMPILER
NAMES $ENV{g++-10} g++-10 PATHS ENV PATH NO_DEFAULT_PATH REQUIRED)
endif()
endif()
Problem
The compiler is not set to g++ when the version of clang++ is less than 10, but I could check that cmake passes the branch
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 10)
I do not understand this behavior. And are there any alternative to this without using command line arguments?
UPDATE
This question was asked in acknowledgment of the fact that setting a compiler in CMakeLists.txt is discouraged.
#KamilCuk suggested two ways to achieve what I stated, and one may take those suggestions if they want to.
Here's what I did.
TL;DR
Do not specify a compiler in CMakeLists.txt.
My suggestion
This is contrary to what I have previously done in this question.
I scrapped all the configuration logic from CMakeLists.txt and decided to create a shell file that extracts compiler versions and select an appropriate compiler. This way of configuration is quite well-known, which can be found in many popular repositories such as ImageMagick and tensorflow.

If you want to write the logic in cmake, you could write something along:
cmake_minimum_required(VERSION 3.11)
# Before project()!!!
execute_process(COMMAND clang++ --version OUTPUT_VARIABLE result)
string(REGEX REPLACE "[^0-9]* ([0-9]+).*" "\\1" clang_version "${result}") # extract the version with some regex
execute_process(COMMAND g++ --version OUTPUT_VARIABLE result)
string(REGEX REPLACE "[^0-9]* ([0-9]+).*" "\\1" gcc_version "${result}") # extract the version with some regex
# write your super condition here and set CMAKE_CXX_COMPILER depending on it
set(CMAKE_CXX_COMPILER g++)
if (gcc_version LESS 10)
set(CMAKE_CXX_COMPILER clang++)
endif()
project(blabla) # uses CMAKE_CXX_COMPILER and configures cmake
You could also use include(CMakeDetermineCXXCompiler) to determine the version, or use the template files from cmake from CMakeCXXCompilerId.cpp.in from cmake installation path that is used by CMakeDetermineCXXCompiler internally.

Related

Compile 2 C++ Libraries with Diffirent C++ Version for each using CMake? [duplicate]

When I try to run a CMake generated makefile to compile my program, I get the error that
range based for loops are not supported in C++ 98 mode.
I tried adding add_definitions(-std=c++0x) to my CMakeLists.txt, but it did not help.
I tried this too:
if(CMAKE_COMPILER_IS_GNUCXX)
add_definitions(-std=gnu++0x)
endif()
When I do g++ --version, I get:
g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
I have also tried SET(CMAKE_CXX_FLAGS "-std=c++0x"), which also does not work.
I do not understand how I can activate C++ 11 features using CMake.
CMake 3.1 introduced the CMAKE_CXX_STANDARD variable that you can use. If you know that you will always have CMake 3.1 or later available, you can just write this in your top-level CMakeLists.txt file, or put it right before any new target is defined:
set (CMAKE_CXX_STANDARD 11)
If you need to support older versions of CMake (quite unlikely these days), here is a macro I came up with that you can use:
macro(use_cxx11)
if (CMAKE_VERSION VERSION_LESS "3.1")
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
endif ()
else ()
set (CMAKE_CXX_STANDARD 11)
endif ()
endmacro(use_cxx11)
The macro only supports GCC right now, but it should be straight-forward to expand it to other compilers.
Then you could write use_cxx11() at the top of any CMakeLists.txt file that defines a target that uses C++11.
CMake issue #15943 for clang users targeting macOS
If you are using CMake and clang to target macOS there is a bug that can cause the CMAKE_CXX_STANDARD feature to simply not work (not add any compiler flags). Make sure that you do one of the following things:
Use cmake_minimum_required to require CMake 3.0 or later, or
Set policy CMP0025 to NEW with the following code at the top of your CMakeLists.txt file before the project command:
# Fix behavior of CMAKE_CXX_STANDARD when targeting macOS.
if (POLICY CMP0025)
cmake_policy(SET CMP0025 NEW)
endif ()
The CMake command target_compile_features() is used to specify the required C++ feature cxx_range_for. CMake will then induce the C++ standard to be used.
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(foobar CXX)
add_executable(foobar main.cc)
target_compile_features(foobar PRIVATE cxx_range_for)
There is no need to use add_definitions(-std=c++11) or to modify the CMake variable CMAKE_CXX_FLAGS, because CMake will make sure the C++ compiler is invoked with the appropriate command line flags.
Maybe your C++ program uses other C++ features than cxx_range_for. The CMake global property CMAKE_CXX_KNOWN_FEATURES lists the C++ features you can choose from.
Instead of using target_compile_features() you can also specify the C++ standard explicitly by setting the CMake properties
CXX_STANDARD
and
CXX_STANDARD_REQUIRED for your CMake target.
See also my more detailed answer.
I am using
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()
But if you want to play with C++11, g++ 4.6.1 is pretty old.
Try to get a newer g++ version.
The easiest way to set the Cxx standard is:
set_property(TARGET tgt PROPERTY CXX_STANDARD 11)
See the CMake documentation for more details.
On modern CMake (>= 3.1) the best way to set global requirements is:
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
It translates to "I want C++11 for all targets, it's not optional, I don’t want to use any GNU or Microsoft extensions."
As of C++17, this still is IMHO the best way.
Source: Enabling C++11 And Later In CMake
As it turns out, SET(CMAKE_CXX_FLAGS "-std=c++0x") does activate many C++11 features. The reason it did not work was that the statement looked like this:
set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")
Following this approach, somehow the -std=c++0x flag was overwritten and it did not work. Setting the flags one by one or using a list method is working.
list( APPEND CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")
For CMake 3.8 and newer you can use
target_compile_features(target PUBLIC cxx_std_11)
If you want the generation step to fail if the toolchain cannot adhere to this standard, you can make this required.
set_target_properties(target PROPERTIES CXX_STANDARD_REQUIRED ON)
If you want strict adherence to standard C++ i.e. avoid C++ extensions offered by your compiler (like GCC's -std=gnu++17), additionally set
set_target_properties(target PROPERTIES CXX_EXTENSIONS OFF)
This is documented in detail at An Introduction to Modern CMake -> Adding Features -> C++11 and Beyond. It also offers advice on how to achieve this on older versions of CMake if you're constrained to those.
The easiest way:
add_compile_options(-std=c++11)
This is another way of enabling C++11 support,
ADD_DEFINITIONS(
-std=c++11 # Or -std=c++0x
# Other flags
)
I have encountered instances where only this method works and other methods fail. Maybe it has something to do with the latest version of CMake.
Modern cmake offers simpler ways to configure compilers to use a specific version of C++. The only thing anyone needs to do is set the relevant target properties. Among the properties supported by cmake, the ones that are used to determine how to configure compilers to support a specific version of C++ are the following:
CXX_STANDARD sets the C++ standard whose features are requested to build the target. Set this as 11 to target C++11.
CXX_EXTENSIONS, a boolean specifying whether compiler specific extensions are requested. Setting this as Off disables support for any compiler-specific extension.
To demonstrate, here is a minimal working example of a CMakeLists.txt.
cmake_minimum_required(VERSION 3.1)
project(testproject LANGUAGES CXX )
set(testproject_SOURCES
main.c++
)
add_executable(testproject ${testproject_SOURCES})
set_target_properties(testproject
PROPERTIES
CXX_STANDARD 11
CXX_EXTENSIONS off
)
In case you want to always activate the latest C++ standard, here's my extension of David Grayson's answer, in light of the recent (CMake 3.8 and CMake 3.11) additions of values of 17 and 20 for CMAKE_CXX_STANDARD):
IF (CMAKE_VERSION VERSION_LESS "3.8")
SET(CMAKE_CXX_STANDARD 14)
ELSEIF (CMAKE_VERSION VERSION_LESS "3.11")
SET(CMAKE_CXX_STANDARD 17)
ELSE()
SET(CMAKE_CXX_STANDARD 20)
ENDIF()
# Typically, you'll also want to turn off compiler-specific extensions:
SET(CMAKE_CXX_EXTENSIONS OFF)
(Use that code in the place of set (CMAKE_CXX_STANDARD 11) in the linked answer.)
What works for me is to set the following line in your CMakeLists.txt:
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
Setting this command activates the C++11 features for the compiler and after executing the cmake .. command, you should be able to use range based for loops in your code and compile it without any errors.
I think just these two lines are enough.
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
The modern way is to specify the minimum required standard to C++11 with:
target_compile_features(foo PUBLIC cxx_std_11)
This way:
CMake can honor default C++ standard of the compiler if it's greater than C++11
You can clearly specify whether C++ standard is required at build time, consume time, or both. This is nice for libraries.
Public compile features are propagated to downstream targets, so it comes for free in those targets even if they don't directly use this feature.
Users can externally set another C++ standard (more recent basically), with CMAKE_CXX_STANDARD, either from command line or CMake presets. If you hardcode CMAKE_CXX_STANDARD in a CMakeLists, nobody can override the C++ standard without editing your CMakeLists, which is not very pleasant.
It requires CMake >= 3.8
You can use the following. This automatically modifies the feature based on your environment.
target_compile_features(your_target INTERFACE cxx_std_20)
For example,
on Gnu/Linux the following adds -std=gnu++20
on Windows with Clang/Ninja it becomes -std=c++20
on Windows with MSVC it becomes /std=c++20
So you support as many as environments possible.
In case you stumble on that same error using cmake as i did.
You need to set
set (CMAKE_CXX_STANDARD 11)
to activate threading because it is only supported from c++11 ++
hope that helps
OS X and Homebrew LLVM related:
Don't forget to call cmake_minimum_required(VERSION 3.3) and project() after it!
Or CMake will insert project() implicitly before line 1, causing trouble with Clang version detection and possibly other sorts of troubles. Here is a related issue.

How to construct CMake files to be OS generic but specific too?

Actually, my project has this files:
/ cmake / CMakeLists.txt
/ sources / {my cpp headers ...}
And I construct the "project" (makefile or .sln...) the same way under every OS, at the root of this repository with the command:
cmake ./cmake/
But it needs some optional settings like the CMAKE_CXX_FLAGS different on each OS.
And I have chosen to put this variables in a /cmake/CMakeCache.txt but to not commit this file (since it is different between OSs). The dev has to generate (edit) this file on each machine. I only gave some instructions in a readme about this CMakeCache file.
How could I make cmake files generic again, but have this differences in a commited content too?
Use code like this in your CMakeLists.txt:
if(UNIX AND NOT APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread")
elseif(WIN32)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DWIN32_LEAN_AND_MEAN")
endif()
Notes:
Append your options to ${CMAKE_CXX_FLAGS} so that user-specified settings are also included.
You cannot use list(APPEND ...) with compiler flags because it uses semicolons to separate parameters (this is why the code above uses set(...) with quotes)
APPLE is also UNIX, so we need NOT APPLE when we actually mean Linux
You can use ifs for different platforms directly in your CMakeLists.txt files like following:
if (APPLE)
# ...
elseif (UNIX)
# ...
elseif (WIN32)
# ...
endif()

How to check the Software version invoked by cmake

I am invoking a software from CMAKE to generate required files for build.Is it possible to print the version of software invoked in the build window..?
As said in the comments, the exact way to output the version will depend on the executable itself.
Lets assume it is <executable> --version.
Then it CMake it will look like:
find_program(EXECUTABLE_RUNTIME <executable>)
if ("${EXECUTABLE_RUNTIME}" STREQUAL "EXECUTABLE_RUNTIME-NOTFOUND")
message(FATAL_ERROR "<executable> runtime could not be found!")
else()
execute_process(COMMAND "${EXECUTABLE_RUNTIME}" --version
OUTPUT_VARIABLE EXECUTABLE_VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE)
message(STATUS "Found <executable> runtime at ${EXECUTABLE_VERSION}, version ${EXECUTABLE_VERSION}")
endif()
A possible footgun is to include the command arguments in the quotes (e.g. "${EXECUTABLE_RUNTIME} --version", if you do this the output variable will be empty.
OUTPUT_STRIP_TRAILING_WHITESPACE will remove the new line which is very often present after the version.

Compiler Flags from CMakeLists.txt don't appear in CMake-Gui or CMakeCache.txt

I just started to learn CMake and thought I would have understood the basic process of first writing the CMakeLists.txt, then configuring to generate the CMakeCache.txtand at the end generating the Makefiles.
However, when I try to apply it to the following CMakeLists.txt, I'm not getting the expected results and I'm not sure what is going wrong. Part of the CMakeLists.txt looks like this:
# compiler flags
if (CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fpermissive -Wall -Wformat-security")
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.8)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-local-typedefs")
endif()
endif()
Since I'm using gcc/g++ 4.7.3, the compiler flags from the first if-statement should be set. But if I configure this with CMake-Gui, there are no compiler flags pre-defined whatsoever. The same happens when I out-comment the if-statements and just keep the set(CMAKE_CXX_FLAGS ...).
When searching the CMakeCache.txt for any -std=c++11 flags, I don't get any results, too.
Why does this happen? What's the point of specifying compiler flags inside the CMakeLists.txt when they aren't used? Or am I getting something completely wrong and they are used, but then I don't know why and how I could check.
When generating the actual (Eclipse CDT) project with make and importing it to Eclipse, I'm getting error messages that C++11 features can't be resolved, the __cplusplus macro contains the value 199711 so the -std=c++11 flag is obviously not used.
The flags you specified in the CMakeLists.txt file are probably correctly used by the compiler. You can't see them directly in CMakeCache.txt but:
You can see command lines by running make VERBOSE=1 instead of standard make
Also, you can set CMAKE_VERBOSE_MAKEFILE to 1 to enable printing of commands (this can be found by checking "Advanced" in CMake GUI)
As #Angew said, if you really want to see the updated flags in the CMake GUI, set your variables with CACHE FORCE
As an example, i use this kind of configuration in a project for some month, and never had problem:
if(MSVC) # MSVC compiler (Win32 only)
# Display more warnings
set(CMAKE_CXX_FLAGS "/W3")
elseif(UNIX OR CMAKE_COMPILER_IS_GNUCXX) # Clang OR Gcc (Linux, Mac OS or Win32 with MingW)
# Enable C++11 and displays all warnings
set(CMAKE_CXX_FLAGS "-Wall -std=c++11")
if(APPLE) # Clang / Mac OS only
# Required on OSX to compile c++11
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++ -mmacosx-version-min=10.7")
endif(APPLE)
endif()
Update:
Starting with CMake 3.0, you can replace set(CMAKE_CXX_FLAGS "...") by add_compile_options(-std=c++11)
CMake 3.1 introduced a new syntax to configure the compiler with specific C++ version:
set(CMAKE_CXX_STANDARD 11)
You can first, set the variable to a value only if it is not in cache already. The last parameter is the description which we don't need since we'll override it anyway.
set(VARIABLE "Hello World!" CACHE STRING "")
Then force the value into cache using its existing value from the line above. Since that is cached, users can still change the variable and it won't be set back every time.
set(VARIABLE ${VARIABLE} CACHE STRING "Description." FORCE)
This is a bit hacky in CMake as you can see, but it works reliably.

how to include NTL using CMake

I use this line to compile a simple program:
g++ main.cc -lntl -lm -lgmp
How do you include this into CMake?
find_package(NTL REQUIRED)
find_package(GMP REQUIRED)
Doesn't work. And gives the following error:
CMake Error at CMakeLists.txt:30 (find_package):
Could not find module FindNTL.cmake or a configuration file for package
NTL.
...
.
and
SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++0x -lntl -lm -lgmp)
Doesn't work either (but I think it's just wrong in general).
Thank you!
If ntl, m, and gmp libraries are usually installed to somewhere in the default path (e.g. /usr/ or /usr/local/), you could simply do something like:
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(Test)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
add_executable(test main.cc)
target_link_libraries(test ntl m gmp)
This is probably closest to your original g++ command, but it isn't very robust however; if any of the libraries aren't found, you won't know about it until you try linking. If you want to fail at configure time (i.e. while running CMake), you could add find_library calls for each of the required libs, e.g.
find_library(NTL_LIB ntl)
if(NOT NTL_LIB)
message(FATAL_ERROR "ntl library not found. Rerun cmake with -DCMAKE_PREFIX_PATH=\"<path to lib1>;<path to lib2>\"")
endif()
You'd then have to change your target_link_libraries command to
target_link_libraries(test ${NTL_LIB} ${M_LIB} ${GMP_LIB})
You'd probably also then have to do a find_file for one of each lib's header files to find out the appropriate path to add via the include_directories command (which translates to -I for g++).
Note, it's important to put quotes around the extra CXX_FLAGS arguments, or CMake treats them like separate values in a list and inserts a semi-colon between the flags.
For further information about find_library, find_file, etc. run:
cmake --help-command find_library
cmake --help-command find_file
Regarding your error:
It doesn't look like there's a FindNTL.cmake module included with CMake. That means you'll have to either:
Write your own FindNTL.cmake,
Find another that somebody else has written,
Hack together a solution that:
Checks if NTL is installed
Provides link targets, relevant flags, etc.
From a (rather quick) Google search, it appears somebody has an NTL module for CMake. Since NTL use GMP, you will probably need the associated GMP module for CMake. It doesn't look like a fully-featured CMake module, but it also appears to be the best thing out there (again, it was a quick Google search, and I don't use NTL).
To use, you'll want to add some things to your CMakeLists.txt:
# Let CMake know where you've put the FindNTL.cmake module.
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/build/CMake/Modules")
# Call the FindNTL module:
find_package(NTL REQUIRED)
SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++0x -lntl -lm -lgmp)
Yes, this is wrong. You don't want to be setting your CXX_FLAGS with linking directives. I would use:
SET ( CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=cxx0x )
to set the Cxx standard you want to use. To actually link to libraries, you'll want to:
Ensure that you've found the libraries (with the relevant find_package ( FOO ) lines)
Link those against your target, like this:
# Build the Foo executable. (Or library, or whatever)
add_executable (FooEXE ${Foo_SOURCES} )
target_link_libraries (FooEXE
${bar_LIBRARIES}
${baz_LIBRARY}
)
Please note! ${bar_LIBRARIES} and ${baz_LIBRARY} is not a typo; there's no standard way of setting the relevant libraries in the FindFOO.cmake modules, which is, in my opinion, an annoyance. If one doesn't work, try the other, or, worst case, have a look in the relevant FindFOO.cmake file (there's a bunch installed with CMake by default) to see what each one uses. With the link i provided, you can use ${NTL_LIB} and ${GMP_LIB}.