†Can static variables be declared in a header file?

You canít declare a static variable without defining it as well (this is because the storage class modifiers static and extern are mutually exclusive). A static variable can be defined in a header file, but this would cause each source file that included the header file to have its own private copy of the variable, which is probably not what was intended. †

Showing Answers 1 - 6 of 6 Answers

Jatin Bhateja

  • May 4th, 2005
 

can we declate static variable as global.Will there be any purpose of making such decleration.

Yes there is difference between declaring a static variable as global and local. If it is local, it can be accessed only in the function where it's declared. But if it is global, all functions can access it. But, what ever be the case, its value will be retained between functions.

paulson paul chambakottukudyil

  • Apr 23rd, 2006
 

A global variable must be declared as static if you want to restrict its access within that file.

vg_220

  • Aug 14th, 2007
 

We are talking C. Isn't it? C doesn't have class construct so please think the 'C' way ! According me, static declaration in a header file should not generally be useful. Can anyone suggest a good use of it?

sssss

  • Nov 11th, 2007
 

In C

The scope of static variable is file. ie., if declared the variable is accessible accross the file.

When declared the vairable in a header then its exposed to where ever its included.  Every file will have a local copy.  You need to extern the variable, ie need to import into other file file externing it.

The suggested way to use is declare it inside a implementation file, it behaves like a private.  If declated it inside a header file it will be made public and exposed to exernal files when used to with extern declaration. The good practice is declare globals in  a header and defile the extern.  so when ever the variable being included it will be imported to that file.  or ther other way is variable can be exposed by using extern.

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

Answer Question

Click here to Login / Register your free account


 
Send   Reset

 

Related Answered Questions

 

Related Open Questions