No, a static variable defined within a file (also known as file-scope static
variable) cannot be accessed directly from another file. The static keyword
in C restricts the scope of a variable to the current file only.
However, if you need to access a variable from another file, you can use one
of the following methods:
1. Function interfaces: Instead of directly accessing the variable, you can
define getter and setter functions in the file where the static variable is
declared. These functions can provide controlled access to the variable.
Other files can then use these functions to read or modify the variable
indirectly.
File1.c:
static int staticVariable; // Define the static variable
int getStaticVariable() {
return staticVariable;
}
void setStaticVariable(int value) {
staticVariable = value;
}
File2.c:
void anotherFunction() {
int value = getStaticVariable(); // Read the staticVariable
setStaticVariable(value + 1); // Modify the staticVariable
}
By using the getter and setter functions, you can access and modify the
value of the static variable indirectly.
To embed this program on your website, copy the following code and paste it into your website's HTML: