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.
Frequently asked questions
How do I fix ld "undefined reference to std::filesystem" (needs -lstdc++fs) in CI?
Link the filesystem library. Add -lstdc++fs (GCC) or -lc++fs (libc++) after your objects.
What does ld "undefined reference to std::filesystem" (needs -lstdc++fs) in CI actually mean?
Code using std::filesystem compiles cleanly, then fails at link with "undefined reference to std::filesystem::..." on an older toolchain.
How do I stop ld "undefined reference to std::filesystem" (needs -lstdc++fs) in CI happening again?
Provision GCC 9+/libc++ 9+ where filesystem is built in, or always link -lstdc++fs/-lc++fs when supporting older toolchains.