c中不同源文件之间的共享变量

0 c variables shared extern

我尝试使用extern在c中的不同源文件之间共享一个全局变量.似乎每个程序都创建了本地不同的变量副本,因此,当程序更改其值时,第二个程序也无法看到更改.我可以修复此问题吗?该计划如下:

的Tools.h

#ifndef  __TOOLS__
#define  __TOOLS__
#include <errno.h>
#include <stdlib.h>

extern int i;

void init();

#endif 
Run Code Online (Sandbox Code Playgroud)

tools.c

#include "tools.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int i;

void init(){

i=0;
}  
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

prog1打印1

prog2打印0(目标是打印1 - 看到值prog1的更改)

Ker*_* SB 5

C语言描述了一个程序的行为.你似乎有多个不同的程序.除了通过I/O系统(FILE*)或系统接口显式地以不依赖于平台的方式(例如,System-V上的共享存储器)之外,不同程序不会彼此交互.