Question about "extern"-clarification
Hello.
Taking the advice from someone on this message board, I have begun reading Bruce Eckel's book "Thinking in C++". And now, for the first time, I have come across mention of the keyword "extern". This is the first time I have run across it, and I have not seen it so far in any of the tutorials I have read on this site.
Well, the author of this book claims you have to use this keyword everytime you want to declare a variable without defining it. Oddly enough, though, I have already declared many variables without defining them, without this keyword, and experienced no trouble. Is it really essential for variable declaration without immediate definition?
For example, here is the some of the text concerning this that I found in this book:
Quote:
In a function declaration, you give a type (the return value), the function name, the argument list, and a semicolon. That’s enough for the compiler to figure out that it’s a declaration and what the function should look like. By inference, a variable declaration might be a type followed by a name. For example:
int a;
could declare the variable a as an integer, using the logic above. Here’s the conflict: there is enough information in the code above for the compiler to create space for an integer called a, and that’s what happens. To resolve this dilemma, a keyword was necessary for C and C++ to say “This is only a declaration; it’s defined elsewhere.” The keyword is extern. It can mean the definition is external to the file, or that the definition occurs later in the file.
Declaring a variable without defining it means using the extern keyword before a description of the variable, like this:
extern int a;
extern can also apply to function declarations. For func1( ), it looks like this:
extern int func1(int length, int width);
This statement is equivalent to the previous func1( ) declarations. Since there is no function body, the compiler must treat it as a function declaration rather than a function definition. The extern keyword is thus superfluous and optional for function declarations. It is probably unfortunate that the designers of C did not require the use of extern for function declarations; it would have been more consistent and less confusing (but would have required more typing, which probably explains the decision).