Search code examples
pythonc++importinclude

C++ #include<XXX.h> equivalent of Python's import XXX as X


I work with Python most of the time, for some reasons now I also need to use C++.

I find Python's import XXX as X very neat in the following way, for example:

import numpy as np
a = np.array([1,2,3])

where I'm very clear by looking at my code that the array() function is provided by the numpy module.

However, when working with C++, if I do:

#include<cstdio>
std::remove(filename);

It's not clear to me at first sight that remove() function under the std namespace is provided by <cstdio>.

So I'm wondering if there is a way to do it in C++ as the import XXX as X way in Python?


Solution

  • Nope.

    It'll be slightly clearer if you write std::remove (which you should be doing anyway; there's no guarantee that the symbol is available in the global namespace) because then at least you'll know it comes from a standard header.

    Beyond that, it's up to your memory. 😊

    Some people try to introduce hacks like:

    namespace SomeThing {
       #include <cstdio>
    }
    
    // Now it's SomeThing::std::remove
    

    That might work for your own headers (though I'd still discourage it even then). But it'll cause all manner of chaos with standard headers for sure and is not permitted:

    [using.headers]/1: The entities in the C++ standard library are defined in headers, whose contents are made available to a translation unit when it contains the appropriate #include preprocessing directive.

    [using.headers]/3: A translation unit shall include a header only outside of any declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header. No diagnostic is required.

    Recall that #include and import are fundamentally different things. C++ modules may go some way towards this sort of functionality, perhaps, but by including source code you are not even touching namespaces of symbols created by that code.