How to just import one function from C++ headers (aka avoiding namespace pollution)

I'm reading codes that designed an OCR model for chemistry. And I see some lines like this
#include <math.h> // fabs(double)
Is it possible to import just one function like what Python does (from module import function)?

I read the code of cmath. When I do #include <cmath>, the inner codes already do #include <math.h> , thus importing all the functions to the global namespace. What should I do?


With most C++ standard library headers, if you don't do using namespace std; they do not pollute the global namespace and put everything into the namespace std instead. So as long as you don't do using namespace std; there will be no pollution.


<math.h>

is a bit different in that regard. It is one of the standard library headers inherited by C++ from C and therefore it doesn't follow the namespace rules of the C++ standard library. C doesn't have namespaces at all and so including the header will put all its names in the global namespace. There is no way to avoid this. Selective inclusion from headers is not possible in C and C++.

There is an alternative form of the same header:

#include <cmath>

This header will put all the standard library functions into the std namespace as for typical C++ standard library headers.

Unfortunately, the C++ standard does allow compilers/standard library implementations to also put the names in the global namespace when <cmath> is included. So even if you use this variant, you have no guarantee that it won't pollute the global namespace and I think indeed most implementations do.


Unfortunately you have to live with C standard library functions which were inherited into C++ polluting the global namespace. I don't think there is anything that can be done about it.

What you can do is put all of your own program's declarations into a namespace, e.g.:

namespace my_stuff {
    // ...
}

If there is a name conflict, then in most situations your own one will be chosen over the global one as long as you are staying in the namespace.