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

标签 c variables shared extern

我曾尝试使用 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/

相关文章:

c - C 中的内部静态变量,你会使用它们吗?

objective-c - 再次声明时可以随机设置变量吗?

c# - RIA 服务中的 Silverlight 共享类导致构建错误 - 类型 'X' 已包含 'Y' 的定义

c - 共享内存 Reader(只读)在 Writer 终止时挂起

c - Hop_Size在aubio中的含义

c - C 中的混洗多维数组

c - 将指针(字符串)深入传递给函数的方式

javascript - block 状 : code variables

android - Android应用程序中的系统可以将静态变量值清零吗?

shared - 在 TFS 2010 中跨不同团队项目共享项目二进制文件