c++gccc++17

experimental::filesystem linker error


I try to use the new c++1z features actually on the head of development within gcc 6.0.

If I try this little example:

#include <iostream>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
int main()
{
    fs::path p1 = "/home/pete/checkit";

    std::cout << "p1 = " << p1 << std::endl;
}

I got:

/opt/linux-gnu_6-20151011/bin/g++ --std=c++1z main.cpp -O2 -g -o go
/tmp/ccaGzqFO.o: In function \`std::experimental::filesystem::v1::__cxx11::path::path(char const (&) [36])':
/opt/linux-gnu_6-20151011/include/c++/6.0.0/experimental/bits/fs_path.h:167: undefined reference to `std::experimental::filesystem::v1::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit status

gcc version is the snapshot linux-gnu_6-20151011

Any hints how to link for the new c++1z features?


Solution

  • The Filesystem TS is nothing to do with C++1z/C++17 support, it is a completely separate specification not part of the C++1z working draft or the final C++17 standard. GCC's implementation of the Filesystem TS (in GCC 5.3 and later) is even available in C++11 mode.

    To use it, you just need to link with -lstdc++fs (or for GCC 13.3 and later, you can use -lstdc++exp instead).

    (The relevant library, libstdc++fs.a, is a static library, so as with any static library it should come after any objects that depend on it in the linker command.)

    Update Nov 2017: as well as the Filesystem TS, GCC 8.x also has an implementation of the C++17 Filesystem library, defined in <filesystem> and in namespace std::filesystem (N.B. no "experimental" in those names). The new C++17 features are available when using -std=gnu++17 or -std=c++17. In GCC 8, the C++17 support was not complete or stable, so for GCC 8 you also need to link to -lstdc++fs for the C++17 Filesystem features.

    Update Jan 2019: starting with GCC 9, the C++17 std::filesystem components are considered stable and can be used without -lstdc++fs (but you still need that library for std::experimental::filesystem).

    Update Apr 2024: starting with GCC 13.3 the std::experimental::filesystem symbols are also available in -lstdc++exp (along with the other experimental definitions, such as a contract violation handler, and std::stacktrace symbols).