How do I share a global variable between c files?

CExtern

C Problem Overview


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?

C Solutions


Solution 1 - C

file 1:

int x = 50;

file 2:

extern int x;

printf("%d", x);

Solution 2 - C

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.

Solution 3 - C

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

Solution 4 - C

In the second .c file use extern keyword with the same variable name.

Solution 5 - C

Do same as you did in file1.c In file2.c:

#include <stdio.h> 

extern int i;  /*This declare that i is an int variable which is defined in some other file*/

int main(void)
{
/* your code*/

If you use int i; in file2.c under main() then i will be treated as local auto variable not the same as defined in file1.c

Solution 6 - C

Use extern keyword in another .c file.

Solution 7 - C

If you want to use global variable i of file1.c in file2.c, then below are the points to remember:

  1. main function shouldn't be there in file2.c
  2. now global variable i can be shared with file2.c by two ways:
    a) by declaring with extern keyword in file2.c i.e extern int i;
    b) by defining the variable i in a header file and including that header file in file2.c.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpeter_perlView Question on Stackoverflow
Solution 1 - CRocky PulleyView Answer on Stackoverflow
Solution 2 - CmdmView Answer on Stackoverflow
Solution 3 - CMurali VPView Answer on Stackoverflow
Solution 4 - CAshaView Answer on Stackoverflow
Solution 5 - CamiView Answer on Stackoverflow
Solution 6 - CKiran PadwalView Answer on Stackoverflow
Solution 7 - Cbharaniprakash tumuView Answer on Stackoverflow