Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I share a global variable between c files?

Tags:

c

extern

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?

like image 896
peter_perl Avatar asked Jul 22 '11 16:07

peter_perl


People also ask

Can I use a global variable from another file 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.

How do I use global variables across files?

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.

How do I use extern to share variables between source files?

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.

How is a variable accessed from another file in C?

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 .


3 Answers

file 1:

int x = 50;

file 2:

extern int x;

printf("%d", x);
like image 144
Rocky Pulley Avatar answered Oct 28 '22 10:10

Rocky Pulley


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.

like image 5
mdm Avatar answered Oct 28 '22 10:10

mdm


using extern <variable type> <variable name> in a header or another C file.

like image 2
Murali VP Avatar answered Oct 28 '22 08:10

Murali VP