我曾尝试使用 extern 在 c 中的不同源文件之间共享一个全局变量。 似乎每个程序都在本地创建变量的不同副本,因此,当一个程序更改其值时,第二个程序也看不到更改的值..我该如何修复?程序如下:
工具.h
#ifndef __TOOLS__
#define __TOOLS__
#include <errno.h>
#include <stdlib.h>
extern int i;
void init();
#endif
工具.c
#include "tools.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
int i;
void init(){
i=0;
}
程序1.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;
}
程序2.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 打印 1
prog2 打印 0(目标是打印 1 - 查看 prog1 所做的值的更改)
最佳答案
C 语言描述了一个 程序的行为。您似乎有多个不同 程序。除了通过 I/O 系统 (FILE*
) 或系统接口(interface)以平台相关的方式(例如 System-V 上的共享内存)显式交互之外,不同的程序不会相互交互。
关于c - c中不同源文件之间的共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794435/