Surjya Narayana Padhi
Surjya Narayana Padhi

Reputation: 7841

How to use a static C variable across multiple files?

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?

Upvotes: 9

Views: 28399

Answers (4)

user9353349
user9353349

Reputation:

Its not recommended, but we can achieve it using pointers with extern storage class.

In 2.c

static int i;
int *globalvar = &i;

In 1.c

extern int *globalvar;

Upvotes: 1

Lundin
Lundin

Reputation: 213306

There is never a reason to access a static variable in another file. You don't seem to know why you are using the static keyword. There are two ways to declare variables at file scope (outside functions).

Global variable

int i;

Advantages:

  • is valid throughout the whole program execution.

Disadvantages:

  • can be accessed with extern to create spaghetti code.
  • "Pollutes" the global namespace.
  • Not thread-safe.
  • Initialized at program startup, which creates program overhead.

Local/private variable

static int i;

Advantages:

  • is valid throughout the whole program execution.
  • Can only be accessed by files in the same "module"/"translation unit" (same .c file).
  • Provides private encapsulation since it cannot be accessed by the caller.

Disadvantages:

  • Not thread-safe.
  • Initialized at program startup, which creates program overhead.

My personal opinion is that there is never a reason to use global variables nor the extern keyword. I have been programming for 15+ years and never needed to use either. I have programmed everything from realtime embedded systems to Windows GUI fluff apps and I have never needed to use global variables in any form of application. Furthermore, they are banned in pretty much every single known C coding standard.

Upvotes: 6

CampaignWizard
CampaignWizard

Reputation: 838

static variables can only be accessed within a single translation unit, which means that only code in the file that it is defined in can see it. The Wikipedia Article has a nice explanation. In this situation, to share the variable across multiple files you would use extern.

Upvotes: 1

Mike Weller
Mike Weller

Reputation: 45598

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;

Upvotes: 15

Related Questions