If I define a global variable in a .c
file, how can I use the same variable in another .c
file?
file1.c
:
#include<stdio.h>
int i=10;
int main()
{
printf("%d",i);
return 0;
}
file2.c
:
#include<stdio.h>
int main()
{
//some data regarding i
printf("%d",i);
return 0;
}
How can the second file file2.c
use the value of i
from the first file file1.c
?
Every C file that wants to use a global variable declared in another file must either #include the appropriate header file or have its own declaration of the variable. Have the variable declared for real in one file only.
To use global variables between files in Python, we can use the global keyword to define a global variable in a module file. Then we can import the module in another module and reference the global variable directly. We import the settings and subfile modules in main.py . Then we call settings.
The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.
The variable number is declared globally and may be accessed from other file when including its declaration with the “ extern ” prefix. However, the variable coefficient is only accessible from the file in which it is declared and only from that point on (it is not visible in function main .
file 1:
int x = 50;
file 2:
extern int x;
printf("%d", x);
Use the extern
keyword to declare the variable in the other .c
file. E.g.:
extern int counter;
means that the actual storage is located in another file. It can be used for both variables and function prototypes.
using extern <variable type> <variable name>
in a header or another C file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With