Problem adding std::filesystem to CMake Project

后端 未结 4 609
余生分开走
余生分开走 2020-12-19 09:29

I am new to CMake projects and I want to use the file system library in my project. I am running Ubuntu 18.04 with GCC 8.2 and CMake 3.13. In order to achieve this I tried t

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-19 10:19

    Besides from @lubgr's answer. I think a more complete way is to also do try_compile to see that you can actually use the filesystem header. This in my opinion is better because some compilers are not supporting std::filesystem yet. Also in gcc 7.x you have the filesystem under experimental namespace. This way you can have a separate try_compile in the else clause and detect that.

    Here is the related cmake for it

    # set everything up for c++ 17 features
    set(CMAKE_CXX_STANDARD 17)
    # Don't add this line if you will try_compile with boost.
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    # test that filesystem header actually is there and works
    try_compile(HAS_FS "${CMAKE_BINARY_DIR}/temp" 
    "${CMAKE_SOURCE_DIR}/tests/has_filesystem.cc" 
                CMAKE_FLAGS -DCMAKE_CXX_STANDARD=17 -DCMAKE_CXX_STANDARD_REQUIRED=ON
                LINK_LIBRARIES stdc++fs)
    if(HAS_FS)
        message(STATUS "Compiler has filesystem support")
    else()
    #   .... You could also try searching for boost::filesystem here.
        message(FATAL_ERROR "Compiler is missing filesystem capabilities")
    endif(HAS_FS)
    

    The file tests/has_filesystem.cc is very simple

    #include 
    
    namespace fs = std::filesystem;
    
    int main()
    {
        fs::path aPath {"../"};
    
        return 0;
    }
    

    You could in your else clause try_compile for boost::filesystem and pass a directive that can be used in your source file where you decide if you want to use c++17 filesystem or boost.

提交回复
热议问题