/ C++, TOOLS

Setting the c++ standard using cmake

cover image adapted from original by Lance Fairbanks licensed under CC BY-SA 3.0

Note: I have written an update to this post here.

I'm currently trying to convert an existing code base from Makefiles to CMake. I'm doing this in order to showcase the advantages we can have by switching to CMake. Its an unofficial conversion, so I am not changing anything in the official repo. I plan on just having a bunch of CMakeLists.txt that I will then use a custom script to copy over the original source tree.

The current code base is using C++98. We plan on changing this, but we need to fight our battles one at a time.

Apparently shared_ptr was changed with C++11 to avoid explicit uses of operator bool. This stackoverflow post explains the issue.

Since I cannot change the code, I need a way to choose which C++ standard the compiler should conform to.

I am also trying to showcase the CMake Visual Studio 12/2013 generator, but our project is currently compiling using a custom flavour of GCC. As such, I wanted to avoid having to fiddle with compiler specific flags in the CMakeLists.txt files, if at all possible.

Luckily, the recently released CMake 3.1 added support for this in the form of the CXX_STANDARD and CXX_STANDARD_REQUIRED properties.

All we need to do is set those properties for the targets we want. For example, considering we have a target named module1:

# set c++ standard to c++98
set_property(TARGET module1 PROPERTY CXX_STANDARD 98)
# ask for c++98 to be required (and not just a best-effort request)
set_property(TARGET module1 PROPERTY CXX_STANDARD_REQUIRED ON)


But when generating the build/project files for Visual Studio, we get this error message:

 

Apparently either the CMake folks don't know what flags to set in Visual Studio to force C++98 compliance (I highly doubt that), or there is no way to ask Visual Studio to conform to a particular standard version.

There is only going forward, no looking back I guess.

I find it sad Visual Studio does not have an equivalent to GCC and Clang's "--std=" flag.

Maybe this will change with Visual Studio 2015 ? I still have to take the technical preview for a spin ;)

rui

Rui Pires

Working as a professional full time remote developer from the Azores since 2011.

Read More