链接到 std++fs - 选择什么语法

Linking to std++fs - what syntax to choose

上下文

我最初使用 gcc 9.2 开发了 C++17 代码,但不得不在只有 gcc 8.2 可用的系统上编译它。

我遇到了 linking 错误:

CMakeFiles/qegg1.dir/qegg1.cpp.o: In function `std::filesystem::exists(std::filesystem::__cxx11::path const&)':
qegg1.cpp:(.text._ZNSt10filesystem6existsERKNS_7__cxx114pathE[_ZNSt10filesystem6existsERKNS_7__cxx114pathE]+0x14): undefined reference to `std::filesystem::status(std::filesystem::__cxx11::path const&)'
CMakeFiles/qegg1.dir/qegg1.cpp.o: In function `std::filesystem::__cxx11::path::path<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::filesystem::__cxx11::path>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::filesystem::__cxx11::path::format)':
qegg1.cpp:(.text._ZNSt10filesystem7__cxx114pathC2INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_EERKT_NS1_6formatE[_ZNSt10filesystem7__cxx114pathC5INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES1_EERKT_NS1_6formatE]+0x64): undefined reference to `std::filesystem::__cxx11::path::_M_split_cmpts()'

解决方案

这些帖子中解释了此错误的解决方案:

根据这些帖子中的答案(简而言之,gcc 8.2 需要一个明确的 link 到文件系统),我通过 linking explicitely 更新了我的 CMakeLists 到 stdc++fs :

set(CMAKE_CXX_STANDARD 17)
# find some dependencies ...
add_executable(myprog myprog.cpp)
target_link_libraries(myprog LINK_PUBLIC ${Boost_LIBRARIES} stdc++fs)

它在我的本地系统 (gcc 9.2) 和远程系统 (gcc 8.2) 上编译得很好,但我不明白为什么。

问题:

此语法与更高版本的 gcc 的兼容性如何以及它与描述 的解决方案相比如何:

set (CMAKE_CXX_FLAGS "-lstdc++fs -std=c++17")

以前,标准库的文件系统部分未包含在 libstdc++ 中,只能通过显式链接到 libstdc++fs 才能使用。 g++ 仍然与 libstdc++fs 一起提供,因此即使对于较新的 g++ 版本,明确链接也不是问题。


我希望找到一种干净的方式来做find_package类似于使用线程时的方式

find_package(Threads REQUIRED)
target_link_libraries(application PRIVATE Threads::Threads)

但不幸的是,我只找到了 Boost::filesystem...

的方法