Home > Software design >  Is there any way to access static global variable defined in main.c and modify it in another file?
Is there any way to access static global variable defined in main.c and modify it in another file?

Time:06-13

For example:

In main.c

static glob_var;

I want to modify the value of glob_var in another file say file1.c

CodePudding user response:

Making an variable static makes its identifier inaccessible from other translation unit (what usually means other C-file). You can either

  1. Make the variable non-static.
//main.c

int glob_var;


//file1.c

extern int glob_var;

Note that the declaration should be put to a header file.

  1. Keep it static and add a helper function for access.
//main.c

static int glob_var;
void SetGlobVar(int val) {
  glob_var = val;
}


//file1.c

void SetGlobVar(int);
void foo(void) {
  SetGlobVar(42);
}

Note that the declaration of SetGlobVar() should be put to a header file.

CodePudding user response:

The comments and other answer address the question of how to access and modify a static global". The following is offed as an alternative to using static for this purpose...

When needing to create a variable that is global and can be changed among several translation units I believe it is more idiomatic to use the externstorage class. This is typically done by:

  • Declaring the extern variable in a header file
  • Defining the extern variable one-time-only in a .c file that #includess the header file.
  • Access and modify the extern class variable from any translation unit that #includes the header file in which the extern is declared.

Example:

in some.h:

void modify_glob_var(int val);
...
extern int glob_var;//declare extern variable

in main.c

#include "some.h"
...
int glob_var = 0;// define extern variable
...
modify_glob_var(10);//access and modify extern variable

in some_other.c

include "some.h"
...
void modify_glob_var(int val)
{
    glob_var = val;//value of extern glob_var is changed here
}
     
  • Related