当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Why clang on Mac automatically includes some missing headers?

问题描述:

I noticed that clang++ includes a missing header - <limits> on Mac, while g++ shows errors about it on Linux. Now I wonder why clang does it, and gcc not. And how I can force clang to not do it.

Here is a sample code which compiles by clang on Mac, but not by gcc on Linux:

#include <iostream>

using namespace std;

int main()

{

cout << "int max: " << numeric_limits<int>::max() << endl;

}

UPD

I looked into libraries and here is what I found.

Internally <iostream> includes <istream>, which defines >> operator for different types. <istream> wants to know limits for short, int and streamsize types.

clang++ uses libc++ standard library, which uses std::numeric_limits class template from <limits> in <istream> for this purpose. That's why this header is included automatically when <iostream> is included.

g++ uses libstdc++ standard library, which uses __gnu_cxx::__numeric_traits class template from <ext/numeric_traits.h> instead of using <limits> in <istream> (<bits/istream.tcc>). There is also a comment in that header which explains why they don't use <limits>:

<limits> is big and we avoid including it

Used compilers:

> clang++ --version

Apple LLVM version 8.0.0 (clang-800.0.42.1)

$ g++ --version

g++ (Debian 4.9.2-10) 4.9.2

网友答案:

In C++, unlike C, standard headers are allowed to #include other standard headers. That sometimes leads to mysterious errors like the ones you're seeing: one compiler's <iostream> includes <limits> and the other doesn't. The solution is to always include the headers needed for whatever names you use. In this case that means to #include <limits> in your code, even though it compiles okay as is with one compiler. There's no harm in #include a header that's already been pulled in, so that's okay with both compilers. It's annoying sometimes, but that's just the way things are.

网友答案:

The clang version of the <iostream> header likely #includes the <limits> header, as such you get it automatically as part of #includeing the <iostream> header.

There's nothing you can do about it. That's how that compiler's library is implemented. You can simply add

#include <limits>

to this file, and it should compile on both platforms.

分享给朋友:
您可能感兴趣的文章:
随机阅读: