简体   繁体   English

h文件中的静态关键字和内部链接

[英]static keyword in h file and internal linkage

Yet another static question. 又一个static问题。 I have read the following: 我看过以下内容:

And I still fail to understand the following behavior: I have one h file: 我仍然无法理解以下行为:我有一个h文件:

// StaticTest.h
#include <stdio.h>

static int counter = 0;

struct A {
    A () {
        counter++;
        printf("In A's ctor(%d)\n", counter);
    }
    ~A () {
        counter--;
        printf("In A's dtor(%d)\n", counter);
    }
};

static A a;

And two cpp files: 还有两个cpp文件:

// StaticTest1.cpp
#include "StaticTest.h"

int main () {
 return 0;
}

And: 和:

// StaticTest2.cpp
#include "StaticTest.h"

The output of the program is: 该计划的输出是:

In A's ctor(1)
In A's ctor(2)
In A's dtor(1)
In A's dtor(0)

Now, A 's constructor is called twice, since the h file is included twice, and since A 's instance named a is declared static , it has internal linkage and the compiler is happy. 现在, A的构造函数被调用两次,因为h文件被包含两次,并且因为A的名为a的实例被声明为static ,所以它具有内部链接并且编译器很高兴。 Since the counter is also declared static, it also has internal linkage, and I would expect that it's value will not be shared in the two cpp files --- but the program output implies the value is shared, since it counts up to 2. 由于counter也被声明为静态,它也有内部链接,我希望它的值不会在两个cpp文件中共享---但是程序输出意味着值是共享的,因为它最多计数2。

any insights? 任何见解?

EDIT: Any answers regarding what is considered a "good programming habit" in the context of declaring static variables in h vs. cpp files is also welcomed. 编辑:在hcpp文件中声明静态变量的上下文中,任何关于被认为是“良好的编程习惯”的答案也受到欢迎。

If StaticTest.h is shared between difference source files then you will get undefined behaviour. 如果不同源文件之间共享StaticTest.h那么您将获得未定义的行为。

If you define a class or inline functions in different translation units then their definitions must be the same (same sequence of tokens) and, crucially, any identifiers must refer to the same entity (unless a const object with internal linkage) as in the definition in another translation unit. 如果您在不同的翻译单元中定义类或内联函数,那么它们的定义必须相同(相同的标记序列),并且至关重要的是,任何标识符必须引用相同的实体(除非具有内部链接的const对象),如定义中所示在另一个翻译单位。

You violate this because counter has internal linkage so in different translation units the identifier in the function definitions refers to a different object. 您违反此规则是因为counter具有内部链接,因此在不同的翻译单元中,函数定义中的标识符指的是不同的对象。

Reference: C++03 3.2 [basic.def.odr] / 5. 参考:C ++ 03 3.2 [basic.def.odr] / 5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM