Search code examples
clinkerglobal-variables

How can I access and modify a global variable across multiple files?


Like the title says, I want to create a system where two programs can access and modify the same global variable.

I've created a directory that has the files 1.c, 2.c, foo.c, and foo.h.

1.c:

#include <unistd.h>
#include <stdio.h>
#include "foo.h"

int main(){
    printf("foo is %d\n", foo);
    sleep(7);
    printf("now foo is %d\n", foo);
}

2.c:

#include <stdio.h>
#include "foo.h"

int main(){
    increment();
    printf("2.c is incrementing foo. foo is now %d\n", foo);
}

foo.h:

#ifndef FOO_H
#define FOO_H

extern int foo;
void increment(void);

#endif

foo.c:

#include <stdlib.h>
#include "foo.h"

int foo = 5;

void increment(){
    ++foo;
}

I compile with the following compilation commands:

gcc -c foo.c
gcc 1.c foo.o -o 1.out
gcc 2.c foo.o -o 2.out

And then I run it with ./1.out ./2.out, ensuring that 2.out runs before the sleep() finishes in 1.out. The result is the following:

./1.out 
foo is 5
now foo is 5
./2.out 
2.c is incrementing foo. foo is now 6

My theory is that when 1.c and 2.c are linked with foo.o, they both get their own local copies of foo, and thus when one program modifies foo the other program's version goes unmodified. Is it possible to create one global variable that can be shared and modified across multiple files?


Solution

  • In C, global variables are global to the execution unit (process), not global to the execution environment (system). Standard C does not provide a mechanism to share memory between processes. However, your platform (Linux, Windows, MacOS, etc.) probably does. Look up "shared memory".