c++includestdclang-tidy

Can I get clang-tidy to warn about the use of indirectly-included standard library constructs


Consider the following program:

#include <array>

int main() {
    throw std::logic_error("hi");
}

With some C++ compilers (or rather, standard libraries) - this compiles. For example, libstdc++ 8, where <array> includes <stdexcept>. But in other standard library implementations, like libstdc++ 11 - this won't compile.

Can I get clang-tidy to warn me about such situations? At least w.r.t. the standard library?

If not - is there another tool, perhaps not clang-based, which can help me detect this issue?


Solution

  • Yes, the check you're looking for is misc-include-cleaner (link). It's there from LLVM 17.0.1.

    Your example fails to compile because error: ‘logic_error’ is not a member of ‘std’, but I believe it's no mistake on your part because that's exactly the reason we prevent indirect includes. Here's one that demonstrates the check for me - and perhaps not for you:

    #include <algorithm>
    
    int main() {
        std::initializer_list<int> i;
    }
    

    I just used Checks: 'misc-include-cleaner' in otherwise default config and clang-tidy says

    warning: included header algorithm is not used directly [misc-include-cleaner]
    ...
    warning: no header providing "std::initializer_list" is directly included [misc-include-cleaner]