Is there any possible use of using extern variable in a file that is not included in any other file?

162 Views Asked by At

I've encountered many examples on the web, that have extern int x in main.c, where the main function lies.

The only use of extern I'm aware of, is to make a declaration in another file, and use it in another file, after defining it.

Like : a.h : extern int x;

a.c : int x = 5;

main.c : #include "a.h" // and start using x

The 1st case seems redundant to me.

So, Is there any possible use of using an extern variable in a file that is not included in any other file?

4

There are 4 best solutions below

7
AudioBubble On BEST ANSWER

extern tells the compiler that x exists in a different module and should be linked from elsewhere. Putting it in main.c directly just avoids pulling in a header (which would be included in-line anyways)

Just like in a header, x still needs to exist in another .c module where it isn't defined extern.

0
Luchian Grigore On

Of course. Using extern in a file lets you use that variable in that file. It doesn't have to be included anywhere else.

3
pratZ On

extern variable has basically two functions one is to use the variable in the other file and the other is to access global variables as in the following code.

int x=10;
int main()
{
     int x=20;
     cout<<x;             //refers to x=20
     if(x==20)
     {
            extern int x;
            cout<<x;      //refers to the global x that is x=10
     }
 }
0
James Kanze On

The use of extern causes the object to have external linkage; to instantiate a template with a object (and not a value or a type), the object has to have external linkage (at least in C++03). Most objects defined in namespace scope have global linkage, but const objects don't. So you have something like:

template <char const* n>
class Toto { /* ... */ };

char const n1[] = "abc";
Toto<n1> t1;    //  Illegal...

extern char const n2[] = "xyz";
Toto<n2> t2;    //  Legal...

It's sort of a special case, but it has led me (once or twice) to use extern in an unnamed namespace in a source file.