18

I am wondering why in the following code, the namespace filesystem is not found:

g++ -std=c++17 main.cpp -lstdc++

// #include <filesystem>   <- error, so changed to the following:
#include <experimental/filesystem>

namespace fs = std::filesystem;

int main()
{
    return 0;
}

error:

main.cpp:3:21: error: ‘filesystem’ is not a namespace-name
 namespace fs = std::filesystem;
                     ^
main.cpp:3:31: error: expected namespace-name before ‘;’ token
 namespace fs = std::filesystem;

gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)

ar2015
  • 5,558
  • 8
  • 53
  • 110
  • 4
    If your compiler is older than the standard you are trying to use, there is only so much compliance you can expect. – Baum mit Augen Jan 18 '18 at 01:29
  • 2
    `std::filesystem` support in g++ starts at version 8.0 – M.M Jan 18 '18 at 01:42
  • Also, to be able to link, you have to add the `-lstdc++fs` option to g++. See notes in https://en.cppreference.com/w/cpp/filesystem – Pierre Jul 20 '20 at 09:08
  • Works fine for me in `g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0` – Dmitry Messerman Oct 04 '21 at 15:08
  • Even compiler is new, if project is not configured with 17 support then, you will see this error: in CMAKE set(CMAKE_CXX_STANDARD 17), will fix the problem. In Autoconf you also need to update C++ version. – Kemin Zhou Aug 14 '23 at 22:57

3 Answers3

26

GCC 5.4.0 was released in June of 2016; over a year before the C++17 standard was adopted. It and its version of libstdc++ have very limited C++17 support. You can see when GCC added C++17 language features here and when libstdc++ added C++17 standard library features here.

At the time of GCC 5.4's release, the filesystem library was not yet implemented in the std::filesystem namespace. It, along with any other <experimental/...> headers that are included in that version, are in the std::experimental namespace.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • 1
    Do you know any solution for that? – Wafula Samuel Nov 20 '18 at 08:58
  • 3
    @SamZiggler Any solution for what? If you must use an old compiler, then you'll have to include the appropriate experimental header and use `std::experimental::filesystem`. You could use some preprocessor checks to set things up if you want to be compatible with a wide range of compiler versions. – Miles Budnek Nov 20 '18 at 16:36
21

<experimental/..> means experimental namespace:

namespace fs = std::experimental::filesystem;

See: http://en.cppreference.com/w/cpp/experimental/fs/path

Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
0

If you are using visual studio go and change the C++ language standard

  • Right-click the project name
  • Go to the general tab and select the Iso c++ 20 enter image description here
M.Ali El-Sayed
  • 1,608
  • 20
  • 23