I have a header file (.h) that is included in multiple .c files. In this header file, there is a variable declared as static. Since the header file is included in multiple files, there can be multiple accesses to that variable.
I’m curious to know the purpose or usefulness of using the static qualifier in this scenario. What is the significance of declaring a variable as static in a header file that is included in multiple .c files?
When we declare a variable as static, what we are doing is providing the access of that variable to the whole file.
Any function can in that specific file can access it.
Generally when we want to share the variable’s value between many files in the project, we set the variable as static and write get/set functions which are external mostly to read the value of static variable.
Hello,
Yes. If you declare static variables into header file and that file is included into multiple c or cpp source files then each file contains separate copy of that variables which can be shared and accessed it.
But, It depends on like how you are going to access it and use it.
Here we declare variable as a global scope.
If a variable is declared as static at the global scope within a header file (.h file) that is included in multiple .c files, each translation unit (.c file) will have its own private copy of that variable. This means that each file that includes the header will have its own independent instance of the variable, even though they have the same name.
However, it’s worth noting that including a header file with static variables in multiple translation units can lead to a waste of memory, as each file will have its own separate copy. In general, it is considered best practice to avoid defining variables in header files and instead declare them as extern in the header and define them in a single source file to maintain a single instance of the variable
In header it’s just declaration, not definition.
Static variable or function scope is limited to that file only and it lives till the execution of program that means it’s not located on stack which is exists in RAM.
In short static means scope limited to that file.
you can use and modify static variables using get and set methods.
have a read here :
https://aticleworld.com/local-static-and-global-variables-in-c/