1.11M Members

How exactly to use extern?

 
0
 

I know this is a really sad question to ask, but please tell me... how and when should I ever use extern?

I recall an example that Narue showed me but even if I read through the definition from MSDN.com as well as other sources, I still can't quite understand the whole "extern" call.

If someone could please provide me with an example, that would be great. I'll keep looking it up and experimenting in the mean time.

-Alex

 
1
 

The extern keyword is used to tell the compiler that a data object is declared in a different *.cpp or *.c file (code unit). Its required for data objects but optional for function declarations. For example, you have two *.cpp files named A.cpp and B.cpp. B.cpp has a global int that needs to be used in A.cpp.

// A.cpp
#include <iostream>
// other includes here
...
extern int hours; // this is declared globally in B.cpp

int foo()
{
     hours = 1;
}
// B.cpp
#include <iostream>
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line

int main()
{
    foo();
}
Question Answered as of 6 Years Ago by Ancient Dragon
 
0
 

Thanks. I never really understood that because my projects always consisted of header files and a main .cpp file - never would I have multiple .cpp's together so it's no wonder that I couldn't explore that idea properly.

I'll experiment by getting used to having multiple .cpp files and headers at the same time - thanks.

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article