How to fix C++ link errors such as "undefined reference to std::filesystem::..."
Problem:
While compiling/linking your C++ project using GCC or Clang you see error messages such as
/usr/bin/ld: CMakeFiles/myproject.dir/main.cpp.o: in function `main':
main.cpp:(.text+0x44d): undefined reference to `std::filesystem::create_directories(std::filesystem::__cxx11::path const&)'
/usr/bin/ld: CMakeFiles/myproject.dir/main.cpp.o: in function `std::filesystem::__cxx11::path::path<char [7], std::filesystem::__cxx11::path>(char const (&) [7], std::filesystem::__cxx11::path::format)':
main.cpp:(.text._ZNSt10filesystem7__cxx114pathC2IA7_cS1_EERKT_NS1_6formatE[_ZNSt10filesystem7__cxx114pathC5IA7_cS1_EERKT_NS1_6formatE]+0x5e): undefined reference to `std::filesystem::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/myproject.dir/build.make:84: myproject] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/myproject.dir/all] Error 2
make: *** [Makefile:84: all] Error 2
Solution
You need to link the stdc++fs
library which comes with your compiler and implements the std::filesystem
functionality.
Link it by adding -lstdc++fs
to your compiler flags.