Kostiantyn Ponomarenko Kostiantyn Ponomarenko - 2 months ago 33
C++ Question

Why clang on Mac automatically includes some missing headers?

I noticed that clang++ includes a missing header -

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;


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.