0

Can we include static variable in header files. If yes,Can other files can access it ?

Can we include static function in header files and use it in another files.

Can we pass static variable as function arguments ?suppose some function is there in header file header.h :

fun(static int a,static int b)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
alisha
  • 39
  • 8
  • Sorry, but are you thinking at header files (i.e. ".h") or c files (i.e. ".c")? Because you want to include it in a header file but then make an example using it in a c file. As for your question, however, you should never define a variable in a header file (because multiple inclusions would mean multiple defines). And if you define them as static in a c file, you don't want it to be seen from other c files. Read the answer to [this](http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program) post to understand the static keyword behavior – frarugi87 Jul 09 '15 at 09:14
  • Please explain what you're trying to achieve, and you might get more useful answers. – domen Jul 09 '15 at 09:33

4 Answers4

2

Any name declared in the global namespace with specifier static has internal linkage. This means that the name is visible within the translation unit where it is declared.

So if a header with a declaration of a name with static keyword is included in several translation units then each translation unit will have its own variable with such a name.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

This is incorrect coding practice to use static variable in header files. Also static limits the scope of variable to a file. So, static variable of file1.c can't be accessed from file2.c

Pawan
  • 1,537
  • 1
  • 15
  • 19
1

You can declare static variable in header files but this variable scope will only be that *.c file in which this header file will be included.

Pushpendra
  • 459
  • 1
  • 4
  • 18
1
  1. A static variable can be defined in the header file. But doing so, the result will be having a private copy of that variable in each source file which includes the header file. So it will be wise not to declare a static variable in header file, unless you are dealing with a different scenario.

  2. Same applies for static function.

  3. Trying to apply static to a function argument doesn't make much sense, so the standard doesn't allow it (§6.7.5.3/2: "The only storage-class specifier that shall occur in a parameter declaration is register.") trying to enter static variable as an argument type results in error.