ld "undefined reference to std::filesystem" (needs -lstdc++fs) in CI
On GCC before 9 and Clang/libc++ before 9, std::filesystem lives in a standalone library. Code compiles but linking fails unless you add -lstdc++fs (GCC) or -lc++fs (libc++).
What this error means
Code using std::filesystem compiles cleanly, then fails at link with "undefined reference to std::filesystem::..." on an older toolchain.
ld
/usr/bin/ld: main.o: undefined reference to
'std::filesystem::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit statusCommon causes
How to fix it
Link the filesystem library
- Add -lstdc++fs (GCC) or -lc++fs (libc++) after your objects.
- In CMake link stdc++fs to the target on older compilers.
ld
g++ -std=c++17 main.cpp -o app -lstdc++fs
# CMake (older GCC)
target_link_libraries(app PRIVATE stdc++fs)How to prevent it
- Provision GCC 9+/libc++ 9+ where filesystem is built in, or always link -lstdc++fs/-lc++fs when supporting older toolchains.
Related guides
gcc/clang "'X' was not declared" needing <filesystem>/<charconv> in CIFix gcc/clang errors for facilities like std::filesystem or std::optional in CI - the modern standard header…
ld "undefined reference to std::__throw_*" (libstdc++ version) in CIFix ld "undefined reference to std::__throw_..." in CI - objects built against a newer libstdc++ are linked t…