Why does clang on Mac automatically include some missing headers?

I noticed that clang ++ contains the missing header - <limits> on the Mac, and g ++ shows errors about this on Linux. Now I wonder why clang does this, but gcc doesn't. And how can I get clang not to do this.

Here is an example of code that compiles clang on a Mac, but not using gcc on Linux:

 #include <iostream> using namespace std; int main() { cout << "int max: " << numeric_limits<int>::max() << endl; } 

UPD

I looked through the libraries, and here is what I found.

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

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

g ++ uses the standard libstdC ++ 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 a comment in this header that explains why they do not use <limits> :

<limits> big and we don't turn it on

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 
+1
c ++ gcc include clang
source share
2 answers

In C ++, unlike C, standard headers are allowed to #include other standard headers. This sometimes leads to mysterious errors, like the ones you see: one <iostream> compiler includes <limits> , and the other does not. The solution is to always include the headers needed for any names you use. In this case, this means #include <limits> in your code, even if it compiles in the same way as with a single compiler. There is no harm in the #include header that has already been pulled in, so everything is fine with both compilers. Sometimes it is annoying, but it is as it is.

+3
source share

The clang version of the <iostream> header is probably #include <limits> header, so you automatically get it as part of the #include <iostream> header.

There is nothing you can do about it. How this compiler library is implemented. You can just add

 #include <limits> 

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

-one
source share

All Articles