【发布时间】:2021-08-12 23:05:09
【问题描述】:
上下文
我最初使用gcc 9.2 开发了一个C++17 代码,但必须在只有gcc 8.2 可用的系统上编译它。
我遇到了链接错误:
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()'
解决方案
这些帖子中解释了此错误的解决方案:
- std::filesystem link error on ubuntu 18.10
- Link errors using <filesystem> members in C++17
- Undefined reference error with new filesystem library and clang++7
按照这些帖子中的答案(简而言之,gcc 8.2 需要明确链接到文件系统),我通过明确链接到 stdc++fs 来更新我的 CMakeLists:
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 的兼容性如何,它与解决方案相比如何描述here 编写:
set (CMAKE_CXX_FLAGS "-lstdc++fs -std=c++17")
【问题讨论】:
-
将选项
-l放入变量CMAKE_CXX_FLAGS永远不是解决方案:stackoverflow.com/questions/43136418/… -
谢谢@Tsyvarev!它证实了我从关于 cmake 的旧讲座中所记得的内容(或多或少的设置标志应该引起审问)。但是,如何在 gcc >= 9.2 时指定
stdc++fs选项不会触发警告或错误? -
以前,标准库的文件系统部分不包含在
libstdc++中,但只能通过显式链接libstdc++fs才能使用。g++仍与libstdc++fs一起提供,因此即使对于较新的g++版本,明确链接也不是问题。 -
这是一个完美的解释,谢谢!
-
@ArnaudBecheler :-) 好的,完成!我真的希望能够提供一种更简洁的方式来使用 CMake 指定库依赖项,但我找不到它:-(
标签: c++ gcc cmake compiler-errors