如何修复 GCC undefined reference to std::experimental::filesystem::...

问题:

你想使用 GCC/G++ 编译使用 std::experimental::filesystem 功能的可执行文件,但在编译/链接期间收到类似这样的错误消息:

linker-error-stdc++fs.txt
test.cpp:(.text+0x33): undefined reference to `std::experimental::filesystem::v1::file_size(std::experimental::filesystem::v1::__cxx11::path const&)'
/tmp/ccSXeCVb.o: In function `std::experimental::filesystem::v1::__cxx11::path::path<char [9], std::experimental::filesystem::v1::__cxx11::path>(char const (&) [9])':
test.cpp:(.text._ZNSt12experimental10filesystem2v17__cxx114pathC2IA9_cS3_EERKT_[_ZNSt12experimental10filesystem2v17__cxx114pathC5IA9_cS3_EERKT_]+0x73): undefined reference to `std::experimental::filesystem::v1::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit status

解决方案

你需要链接 stdc++fs 库,即在 g++ 命令后附加 -lstdc++fs

例如,有效的命令如下所示:

build-with-stdc++fs.sh
g++ -o myprogram main.cpp -lstdc++fs

Check out similar posts by category: C/C++, GCC Errors