Search code examples
c++cmakeconan

How to propagate conan's compiler.cppstd setting to the compiler when building a library with CMake?


If you build a library with conan and set compiler.cppstd setting to e.g. 20 and call conan install, the libraries are still built with the default standard for the given compiler.

The docs say:

The value of compiler.cppstd provided by the consumer is used by the build helpers:

  • The CMake build helper will set the CONAN_CMAKE_CXX_STANDARD and CONAN_CMAKE_CXX_EXTENSIONS definitions that will be converted to the corresponding CMake variables to activate the standard automatically with the conan_basic_setup() macro.

So it looks like you need to call conan_basic_setup() to activate this setting. But how do I call it? By patching a library's CMakeLists.txt? I sure don't want to do that just to have the proper standard version used. I can see some recipes that manually set the CMake definition based on the setting, e.g.:

But this feels like a hack either. So what is the proper way to make sure libraries are built with the compiler.cppstd I specified?


Solution

  • Avoid patching, it's ugly and fragile, for each new release you will need an update due upstream's changes.

    The main approach is a CMakeLists.txt as wrapper, as real example: https://github.com/conan-io/conan-center-index/blob/5f77986125ee05c4833b0946589b03b751bf634a/recipes/proposal/all/CMakeLists.txt and there many others.

    cmake_minimum_required(VERSION 3.1)
    project(cmake_wrapper)
    
    include(conanbuildinfo.cmake)
    conan_basic_setup(KEEP_RPATHS)
    
    add_subdirectory(source_subfolder)
    

    The important thing here is including conanbuildinfo.cmake which is generated by cmake Conan generator, then the CMake helper will do the rest.

    The source_subfolder here is project source folder, then the main CMakeLists.txt will be loaded after configuring all Conan settings.