himanshu sachdeva
himanshu sachdeva

Reputation: 11

Access global variable value in different .c files present in different paths

I have 2 files: Sod/iload/iload.c and Item/itemrule/itemrule.c, and I want to access a variable defined in iload.c which is defined in itemrule.c.

To do this, I made and defined a global variable in iload.c, and I tried to access this variable in itemrule .c with the extern keyword, but it is always 0.

I'm worried that it might be because the files have different paths, does anyone know how I can access this variable?

Upvotes: 1

Views: 68

Answers (2)

Andy J
Andy J

Reputation: 1545

I would like to offer an alternative to Gene's answer. In my experience there are two main ways to share variables across modules (compilation units):

1) "Getters and Setters".

2) Externs.

Depending on what kind of team you're working with, they'll have a preference for one or the other. C functions by default have external linkage; you need to force internal linkage via the static keyword in front of the function name if you don't want this.

1) Getters and Setters:

// foo.c
#include <stdio.h>
int my_global_var = 0;
...

Then you can follow it with externally-linked getters and setters. i.e.:

int get_my_global_var(void)
{
  return my_global_var;
}

void set_my_global_var(int var)
{
  my_global_var = var;
}

This is done within the c file (module). It will be the getters and setters will be able to be called from any other module and they will get and set the global variable my_global_var.

2) Externs:

// foo.c
#include <stdio.h>
int my_global_var = 0;
...

An alternative to getters and setters is to use externs. In this case you add nothing extra to the module that contains the global variable you wish to access/modify (my_global_var).

// bar.c
#include <stdio.h>
extern int my_global_var;
...

Notice the syntax here; when we use the extern keyword, we don't initialize it as anything. We are simply infoming the compiler that the global variable my_global_var has external linkage.

Upvotes: 0

Gene
Gene

Reputation: 47020

The usual idiom is to use an extern declaration in a header file and include that wherever the global is needed.

// foo.h
// Make the global visible in any C file that includes this header.
extern int my_global_var;
// foo.c
#include "foo.h" // Not really needed here, but fine.
int my_global_var;
...
// bar.c
#include <stdio.h>
#include "foo.h" // This one makes the global visible in the rest of the file.

void do_something(void) {
  printf("my global var's value is: %d\n", my_global_var);
}

Note that using globals like this in a program of any significant size or complexity can lead to messy, bug-prone, and hard-to-change code. Not a great pattern to follow.

Upvotes: 2

Related Questions