在C中使用extern不能按预期工作

时间:2021-12-09 03:14:07

I have created two files:

我创建了两个文件:

tunables.h

#ifndef TUNABLES_H
#define TUNABLES_H

void tunables_load_conservative();
void tunables_load_aggressive();

extern int timer_x;
#endif /*TUNABLES_H */

and tunables.c

#include "tunables.h"

int timer_x;

void tunables_load_conservative(){
     timer_x = 3;
}
void tunables_load_aggressive(){
     timer_x = 1;
}

All the other files of my project includes "tunables.h". When I load the project both A.c and B.c calls tunables_load_conservative but if, after a while, I call in file A.c tunables_load_aggressive() in file B.c the timer_x remains 3. Why?

我项目的所有其他文件都包含“tunables.h”。当我加载项目时,A.c和B.c都调用了tunables_load_conservative但是,如果过了一段时间,我在文件B.c中调用文件A.c tunables_load_aggressive(),timer_x仍为3.为什么?

This is my Makefile:

这是我的Makefile:

INCLUDE=`pwd`/include
GCCFLAGS= -ansi -O3 -pedantic -Wall -Wunused -I${INCLUDE} -DDEBUG 
GCCOTHERFLAGS= -ggdb -pg

all: A B

A: A.o tunables.o
    gcc -o A ${GCCFLAGS} ${GCCOTHERFLAGS} tunables.o

B: B.o tunables.o
    gcc -o LBfixed ${GCCFLAGS} ${GCCOTHERFLAGS} tunables.o

A.o: A.c
    gcc -c ${GCCFLAGS} ${GCCOTHERFLAGS} A.c

B.o: B.c
    gcc -c ${GCCFLAGS} ${GCCOTHERFLAGS} B.c

tunables.o: tunables.c
    gcc -c ${GCCFLAGS} ${GCCOTHERFLAGS} tunables.c

clean:
    rm -rf *.o A B

1 个解决方案

#1


4  

It looks like you've got two separate processes, A and B. The extern declaration does not set up shared memory across processes, but instead allows different compilation units within the same process to access the same variable.

看起来你有两个独立的进程,A和B.extern声明不会跨进程设置共享内存,而是允许同一进程中的不同编译单元访问同一个变量。

To share a variable across processes, you will need to use system-dependent IPC methods.

要跨进程共享变量,您需要使用依赖于系统的IPC方法。

#1


4  

It looks like you've got two separate processes, A and B. The extern declaration does not set up shared memory across processes, but instead allows different compilation units within the same process to access the same variable.

看起来你有两个独立的进程,A和B.extern声明不会跨进程设置共享内存,而是允许同一进程中的不同编译单元访问同一个变量。

To share a variable across processes, you will need to use system-dependent IPC methods.

要跨进程共享变量,您需要使用依赖于系统的IPC方法。