Context
I initially developed a C++17 code with gcc 9.2
, but had to compile it on a system that has only gcc 8.2
available.
I had the linking error:
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()'
Solution
The solution to this error is explained in these posts:
- 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
Following the answers in these posts (in short, gcc 8.2
needs an explicit link to filesystem), I updated my CMakeLists by linking explicitely to 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)
It compile fine on my local system (gcc 9.2) and on the remote (gcc 8.2), but I don't understand why.
Question:
How compatible is this syntax with later versions of gcc and how does it compare to the solution describe here to write:
set (CMAKE_CXX_FLAGS "-lstdc++fs -std=c++17")