简体   繁体   中英

Understanding extern in c++

namespace std  
{ 
  extern istream cin;   
...
}

By using extern we declare that cin is defined in some other unit as the answer

But what if istream is defined/undefined in std ,there should be some difference,right?

What is the difference for the compilor?

The compiler does not care. The linker will fail to "link" the externed object to the real object if it is undefined.

The compiler would normally give an error finding that you're using cin without having, at least, declaring it.

With extern, you can tell the compiler "easy, easy, trust me, there is somewhere else a declaration and a definition for a cin of class istream.

Then the linker jumps into action, and the link between the call to the uses of cin and the object itself are specially "pending". The linker has to unite all these calls with their destination, and now is when the fact of cin existing or not (has been compiled or not) has its importance. If not, then the linker fails. The errors provided by the linker are far more cryptic than the ones given by the compiler, but they are interesting to explore, because are a very good way to learn.

For example, the following piece of code does not #include cstdio not stdio.h, but we know that printf will be there, because the standard library is always linked with our program. Yes, it works.

extern int printf(const char *, ...);

int main()
{
    printf( "Hello, world!\n" );
}

The compiler must know that istream is a type, and with the extern keyword you are telling it that std::cin exists and is of that type. if istream has not been declared as a type by the time the compiler sees the line, it will complain telling you that it is not a type.

//extern type var; // error 'type' unknown at this point
class type;
extern type var;   // ok:'type' is a class even if not fully declared

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM