C
Comp1597
I know this is a standard topic and I've done a fair amount of
googling but I'm still a bit confused by extern variables.
My main text is C++ Primer, 4th edition (Lippman, Lajoie and Moo).
For example, I ran the following program:
// Code below in a source file
#include "SomeHeader.h"
#include <iostream>
int main ()
{
int j = doropi;
std::cout << j;
}
//Code in SomeHeader.h
const int doropi = 9;
The result of the program was that 9 was output. However, what I
expected was a compile error based on the rule (or what I thought was
the rule) that const definitions have file scope and that the way to
use consts from other files was via extern.
My code had no extern and yet I was able to use the const anyway.
This made me question the whole purpose of externs. I didn't need the
extern to fetch a member from another file and yet I thought that was
exactly what extern is for.
What I'd be grateful for is a very simple example of a necessary use
of extern variables. Googling gave me lots of definitions but no
examples.
When I tried to create my own examples, I always found that extern was
unnecessary, and that the program ran fine without this concept.
In case the compiler is relevant, I'm using the latest version of
Visual C++ Express.
Many thanks for your help.
googling but I'm still a bit confused by extern variables.
My main text is C++ Primer, 4th edition (Lippman, Lajoie and Moo).
For example, I ran the following program:
// Code below in a source file
#include "SomeHeader.h"
#include <iostream>
int main ()
{
int j = doropi;
std::cout << j;
}
//Code in SomeHeader.h
const int doropi = 9;
The result of the program was that 9 was output. However, what I
expected was a compile error based on the rule (or what I thought was
the rule) that const definitions have file scope and that the way to
use consts from other files was via extern.
My code had no extern and yet I was able to use the const anyway.
This made me question the whole purpose of externs. I didn't need the
extern to fetch a member from another file and yet I thought that was
exactly what extern is for.
What I'd be grateful for is a very simple example of a necessary use
of extern variables. Googling gave me lots of definitions but no
examples.
When I tried to create my own examples, I always found that extern was
unnecessary, and that the program ran fine without this concept.
In case the compiler is relevant, I'm using the latest version of
Visual C++ Express.
Many thanks for your help.