c++cmake

Cmake - select different c++ standard for different sources


As the title suggest, I'd like to use cmake to build a project, and depending on the source file, enforcing a different c++ standard.

The reason is : I am working on a library and would like to make it c++03 compliant for compatibility, but would like to use Google test suite which requires c++11.

So the unit tests would be compiled with c++11, but I'd like my library to fail at compilation if there is reference to a c++11 only feature.


Solution

  • So just do that - ompile your library with one standard, and your tests with the other. Nowadays, https://stackoverflow.com/a/61281312/9072753 method should be preferred.

    add_library(mylib lib1.cpp)
    set_target_properties(mylib
        PROPERTIES
        CXX_STANDARD 03
        CXX_EXTENSIONS off
        )
    
    add_executable(mytest main.cpp)
    set_target_properties(mytest
        PROPERTIES
        CXX_STANDARD 11
        CXX_EXTENSIONS off
        )
    target_link_libraries(mytest PRIVATE mylib)
    add_test(NAME mytest COMMAND mytest)