• ### Announcements

#### Archived

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

# What does extern do?

## Recommended Posts

The subject says it all... --------------------

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

##### Share on other sites
// this is file1.cppint myvar;// this is file2.cppextern 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 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 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;

##### Share on other sites
yes, yanroy.
the extern keyword applies to functions, variables, etc.
HOWEVER, for functions, the parameters must be the same for the extern and the actual declaration.

##### 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 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 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

• ### Forum Statistics

• Total Topics
628281
• Total Posts
2981804

• 9
• 10
• 11
• 17
• 14