I'm trying to figure out how I can have an extern variable across multiple files and be able to change it globally, when I change its value in one file, I expected it to change in all the other files.
For example:
header.h:
#include <stdio.h>
int val = 0;
file1.c:
#include "header.h"
extern int val;
void foo() {
printf("%d\n", val);
}
file2.c:
#include "header.h"
extern int val;
void foo() {
val = 1;
}
So I expected that if I ran file1 I would get 0 printed in the console, but if I ran file2 first and then file1, I would get 1 printed out.
Am I wrong about the way extern works?
Assuming that you are compiling both file1.c and file2.c into a single binary.
For sharing variable between different files you can also use #defines and #ifdef macros.
i. declare #define __MAIN__
(this is just for example, it could be anything) at start of the files before all include statement in one of the .c file
ii. in header.h you can do the following,
#ifdef __MAIN__
int val = 0;
#else
extern int val;
Assuming that both file1.c and file2.c will be compiled into different binary and while running both will act as 2 different process then:
i. There are IPC techniques for communications between 2 process, for your case shared memory would be appropriate.
ii. You can use System V shared memory or POSIX shared memory, following links are here for reference.
System V: https://www.geeksforgeeks.org/ipc-shared-memory/
POSIX : https://www.geeksforgeeks.org/posix-shared-memory-api/