Why clang on Mac automatically includes some missi

2019-07-25 06:53发布

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

2条回答
女痞
2楼-- · 2019-07-25 07:29

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.

查看更多
来,给爷笑一个
3楼-- · 2019-07-25 07:29

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.

查看更多
登录 后发表回答