我学习了C ++文件系统库(std::filesystem
)的用法。以下代码导致链接器错误。
我该如何解决?
fs.cpp
的代码:
#include <iostream>
#include <filesystem>
#include <algorithm>
#include <iterator>
int main() {
using namespace std::filesystem;
directory_iterator iter{"."};
for (auto& ent: iter) {
std::cout << ent.path() << std::endl;
}
}
错误输出:
/usr/bin/ld: /tmp/cc7vhf9X.o: in function `main':
fs.cpp:(.text+0x10b): undefined reference to `std::filesystem::__cxx11::directory_iterator::operator*() const'
/usr/bin/ld: fs.cpp:(.text+0x151): undefined reference to `std::filesystem::__cxx11::directory_iterator::operator++()'
/usr/bin/ld: /tmp/cc7vhf9X.o: in function `std::filesystem::__cxx11::directory_iterator::directory_iterator(std::filesystem::__cxx11::path const&)':
fs.cpp:(.text._ZNSt10filesystem7__cxx1118directory_iteratorC2ERKNS0_4pathE[_ZNSt10filesystem7__cxx1118directory_iteratorC5ERKNS0_4pathE]+0x26): undefined reference to `std::filesystem::__cxx11::directory_iterator::directory_iterator(std::filesystem::__cxx11::path
const&, std::filesystem::directory_options, std::error_code*)'
/usr/bin/ld: /tmp/cc7vhf9X.o: in function `std::filesystem::__cxx11::path::path<char [2], std::filesystem::__cxx11::path>(char const (&) [2], std::filesystem::__cxx11::path::format)':
fs.cpp:(.text._ZNSt10filesystem7__cxx114pathC2IA2_cS1_EERKT_NS1_6formatE[_ZNSt10filesystem7__cxx114pathC5IA2_cS1_EERKT_NS1_6formatE]+0x6d): undefined reference to `std::filesystem::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit status
环境:
g++ -std=c++17 -o fs fs.cpp
答案 0 :(得分:0)
它需要在选项中添加-lstdc++fs
。
g++ -lstdc++fs -std=c++17 -o fs fs.cpp -lstdc++fs