在这种情况下,静态 int 的值会发生变化吗?



>我目前有一个头文件,其中包含多个头文件和源文件。头文件看起来像这样

File:External.h
#ifndef EXTERNAL_H
#define EXTERNAL_H
#include "memory"
static int pid=-1;
#endif // EXTERNAL_H

这是我当前场景的简化,只是为了检查我是否可能错了。现在假设我有两个类foobar。这是我注意到的行为。

#include "External.h"
void foo::someMethod()
{
   pid =13; //Change the value of pid;
   bar_ptr = new bar();
}
//bar constrcutor
#include "External.h"
bar::bar()
{
   int a = pid;  //The value of a is -1 wasnt it suppose to be 13
}
假设

的值不是 13 吗,特别是因为它是静态类型的开放变量(不是结构或类)。

这是因为每个文件都包含标头,因此每个编译单元(大致是源文件)内部都有以下定义:

static int pid=-1;

因此,他们每个人都有自己的副本。

实际上,您应该执行以下操作:

外部.h

// The declaration, so that people can access it
extern int pid;

外部.c

// The actual implementation
int pid = -1;

最新更新