1

I learning usage of C++ filesystem library (std::filesystem). The following code cause linker error.

How I can fix it?

Code for 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;
    }
}

Error output:

/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

Environment:

  • Ubuntu 18.10
  • g++ 8.2.0
  • compile options: g++ -std=c++17 -o fs fs.cpp
jww
  • 97,681
  • 90
  • 411
  • 885
KiYugadgeter
  • 3,796
  • 7
  • 34
  • 74

1 Answers1

25

It need to add -lstdc++fs to option.

g++ -lstdc++fs -std=c++17 -o fs fs.cpp -lstdc++fs
KiYugadgeter
  • 3,796
  • 7
  • 34
  • 74