c++clang-tidystd-filesystem

clang-tidy throws an error when using namespace alias


#include <iostream>
#include <filesystem>

int main()
{
    namespace fs = std::filesystem;

    fs::path sample_text_file_path { "test.txt" };

    std::cout << sample_text_file_path << '\n';
}

Command:

g++ -g test_namespace_alias_clang_tidy.cpp -o out   # compiles fine
clang-tidy -checks=cppcoreguidelines-* test_namespace_alias_clang_tidy.cpp

Errors (from clang-tidy):

Error while processing test_namespace_alias_clang_tidy.cpp.
test_namespace_alias_clang_tidy.cpp:6:25: error: expected namespace name [clang-diagnostic-error]
    namespace fs = std::filesystem;
                   ~~~~~^
test_namespace_alias_clang_tidy.cpp:8:5: error: use of undeclared identifier 'fs' [clang-diagnostic-error]
    fs::path sample_text_file_path { "test.txt" };
    ^
test_namespace_alias_clang_tidy.cpp:8:14: warning: variable 'sample_text_file_path' is not initialized [cppcoreguidelines-init-variables]
    fs::path sample_text_file_path { "test.txt" };
             ^
                                   = 0
$ clang-tidy --version
Ubuntu LLVM version 14.0.0
  
  Optimized build.
  Default target: x86_64-pc-linux-gnu
  Host CPU: skylake

$ g++ --version
g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0

Are these reports valid? If yes, how do I fix these errors?


Solution

  • Since I was using std::filesystem from C++ 17, I had to specify the standard explicitly to clang-tidy since it didn't seem to recognize it.

    I had to use -extra-arg=-std=c++17:

    clang-tidy -extra-arg=-std=c++17 --checks=cppcoreguidelines-* test_namespace_alias_clang_tidy.cpp