A Better way to ask cmake for a C++ standard

Posted by on May 5, 2015 in c++, cmake, tools | One Comment
A Better way to ask cmake for a C++ standard

A while back I wrote a post about how to set the c++ standard with cmake.

It revolved around setting the CXX_STANDARD and optionally CXX_STANDARD_REQUIRED properties.

I have since found this technique does not work as nicely as I would like with Visual Studio.

Setting CXX_STANDARD is just a “soft” request, where we express our wish that that particular standard should be used. It is just a request, and if CMake has no way to fulfil it with the toolset being used, it will still proceed and we might fail horribly when we actually try to compile anything.

With CXX_STANDARD_REQUIRED on the other hand, we are expressing that the specified standard must be used and be fully supported by the compiler.

There are two issues with using this technique with Visual Studio:

1 – It (and quite possibly other compilers) does not support the entirety of the C++11 standard yet. This will force CMake to fail, because it cannot fulfil our request.

2 – Visual Studio has no flag to select what standard to use (unlike gcc and clang). This means that if we wanted to keep our code frozen in C++98/C++03 mode, there is just no way to do it. Also, we are always on their “latest” supported version, there is no going back.

So what can we do?

We can use CMake’s target_compile_features, were we can be more fine grained and specify what language features we want to use.

There is a list of know feature you can choose from, and CMake will make sure they are all available to you, or it will fail when configuring your project. Note that it may not add any compilation flag, if it does not need to.

A special thank you to steveire on Stack Overflow that helped me get this working with my biicode block by answering my question.

1 Comment

  1. Sennin » Setting the c++ standard using cmake
    May 5, 2015

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

    Reply

Leave a Reply