开发者

Using extern in C doesn't work as expected

开发者 https://www.devze.com 2022-12-10 08:19 出处:网络
I have created two files: tunables.h #ifndef TUNABLES_H #define TUNABLES_H void tunables_load_conservative();

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?

This is my Makefile:

INCLUDE=`pwd`/include
GCCFLAGS= -a开发者_JAVA百科nsi -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


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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号