Archived

This topic is now archived and is closed to further replies.

Yanroy

What does extern do?

Recommended Posts


// this is file1.cpp

int myvar;

// this is file2.cpp

extern int myvar; // tell the compiler that we want to use myvar, which is declared in another file.

void f()
{
myvar = anothervar;
...
}


That pretty much sums it up I''d say.

"Paranoia is the belief in a hidden order behind the visible." - Anonymous

Share this post


Link to post
Share on other sites
lets say you have:
extern int counter;
it tells the program: "the variable ''counter'' is defined somewhere else in my project, so don''t worry about it"
lets say you have to access the counter variable before you declare it, like if you have a function in a header file that manipulates ''couner'' before its actually declared in your main file. if you were to just reference ''counter'' in the function, it would give you and undelcared variable error. so, instead of declaring it twice (once in the header and once in the main file), extern tells the program that counter is going to be defined later.
hope you understand my muffled explanation

Share this post


Link to post
Share on other sites
That may have solved the problem in my other thread about library files... I can''t test it right now though.

If I make a lib called test.lib that has a function Hello() in it, then go into my test.h header and define extern Hello(), will that let me use Hello()?

--------------------


You are not a real programmer until you end all your sentences with semicolons;

Yanroy@usa.com

Share this post


Link to post
Share on other sites
You don''t need to use extern for functions. Just for variables. Variables have file scope by default (other files don''t see them unless you use ''extern'' to tell them to look externally) but functions have external scope (unless you specify the function as static to keep it in file scope). Confused yet?

To access a function from another file, just declare the prototype, eg.

int MyFunc();

Share this post


Link to post
Share on other sites
A good idea is to put a global variable in a source file and then put the extern declaration in a header file. Now, all source files who need this variable just have to include that header. The source file with the variable can also include that header.

/Pelle

Share this post


Link to post
Share on other sites
it''s a bit like saying:
"hoy, compiler, this variable exits - take my word for it!"

but using extern implies you are using globals which most of the time is taboo

Share this post


Link to post
Share on other sites