1,105,263 Community Members

How exactly to use extern?

Member Avatar
Alex Edwards
Posting Shark
971 posts since Jun 2008
Reputation Points: 321 [?]
Q&As Helped to Solve: 109 [?]
Skill Endorsements: 2 [?]
 
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

Member Avatar
Ancient Dragon
Achieved Level 70
27,571 posts since Aug 2005
Reputation Points: 5,231 [?]
Q&As Helped to Solve: 3,028 [?]
Skill Endorsements: 115 [?]
Team Colleague
Featured
Sponsor
 
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 5 Years Ago by Ancient Dragon
Member Avatar
Alex Edwards
Posting Shark
971 posts since Jun 2008
Reputation Points: 321 [?]
Q&As Helped to Solve: 109 [?]
Skill Endorsements: 2 [?]
 
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.

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