top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Can static variables be declared in a header file?

+5 votes
519 views

What would be the drawback if we define a static variable in the header file?

posted Nov 17, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

1) 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).
2) 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.

answer Nov 17, 2013 by Salil Agrawal
Similar Questions
+5 votes

You can find three principal uses for the static. This is a good way how to start your answer to this question. Let’s look at the three principal uses:

  1. Firstly, when you declare inside of a function: This retains the value between function calls

  2. Secondly, when it is declared for the function name: By default function is extern..therefore it will be visible out of different files if the function declaration is set as static..it will be invisible for outer files

  3. And lastly, static for global parameters: By default you can use global variables from outside files When it’s static global..this variable will be limited to within the file.

is this right ?

+1 vote
#include<stdio.h>
void fun(static int a);
int main(void)
{
   static int z=0;

   fun(z);

   return 0;
}

void fun(static int a)
{
   printf("%d",a);
}
...