i have tried sharing a global variable between different source files in c using extern. it seems like each program creates locally different copies of the variable and as a result, when a program changes its value which also changes is not visible to the second program..how can i repair this? The program is given below:
tools.h
#ifndef __TOOLS__
#define __TOOLS__
#include <errno.h>
#include <stdlib.h>
extern int i;
void init();
#endif
tools.c
#include "tools.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int i;
void init(){
i=0;
}
prog1.c
#include "tools.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc,char *argv[]){
i=1;
printf("%d\n", i);
return 0;
}
prog2.c
#include "tools.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc,char *argv[]){
sleep(1);
printf("%d\n", i);
return 0;
}
prog1 printed 1
prog2 printed 0 (the target was to print 1 - see the change to the value prog1 did)
maintwice.prog1.cand the other usingprog2.c, then both programs are behaving normal. If you used both of them, you should get a linker error.