Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a static C variable across multiple files?

Tags:

c

file

static

gcc

I have two C files 1.c and 2.c

2.c

#include<stdio.h>

static int i;

int func1(){
   i = 5;
   printf("\nfile2 : %d\n",i);
   return 0;
}

1.c

#include<stdio.h>

int i;

int main()
{
   func1();
   printf("\nFile1: %d\n",i);
   return 0;
}

I compiled both the files with "gcc 1.c 2.c -o st" The output is as follows

file2 : 5

File2: 0

I was expecting output as follows

file2 : 5

File2: 5

I want to access the same variable "i" in both the files. How can I do it?

like image 914
Surjya Narayana Padhi Avatar asked Oct 04 '12 13:10

Surjya Narayana Padhi


People also ask

Can global variables be used in different files?

A global variable is accessible to all functions in every source file where it is declared. To avoid problems: Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error.

Can static variables be shared?

No. It is not possible. Each process is in a separate address space.

Can we declare static variables multiple times?

Static variables can be assigned as many times as you wish. static int count = 0; is initialization and that happens only once, no matter how many times you call demo .

How many possible copies can a static have?

Static Members Only one copy of a static member exists, regardless of how many instances of the class are created.


1 Answers

Choose one file which will store the variable. Do not use static. The whole point of static is to keep the variable private and untouchable by other modules.

In all other files, use the extern keyword to reference the variable:

extern int i;
like image 184
Mike Weller Avatar answered Nov 15 '22 22:11

Mike Weller