We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,453 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

How exactly to use extern?

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

2
Contributors
2
Replies
8 Hours
Discussion Span
4 Years Ago
Last Updated
18
Views
Question
Answered
Alex Edwards
Posting Shark
972 posts since Jun 2008
Reputation Points: 392
Solved Threads: 109
Skill Endorsements: 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();
}
Ancient Dragon
Achieved Level 70
Team Colleague
32,157 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,577
Skill Endorsements: 69
Question Answered as of 4 Years Ago by Ancient Dragon

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.

Alex Edwards
Posting Shark
972 posts since Jun 2008
Reputation Points: 392
Solved Threads: 109
Skill Endorsements: 1

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0640 seconds using 2.67MB