static keyword in h file and internal linkage

柔情痞子 提交于 2019-11-30 06:56:59

问题


Yet another static question. I have read the following:

  • What are static variables?
  • file scope and static floats
  • http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx

And I still fail to understand the following behavior: I have one h file:

// 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:

// 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. 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.

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.


回答1:


If StaticTest.h is shared between difference source files then you will get undefined behaviour.

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.

You violate this because counter has internal linkage so in different translation units the identifier in the function definitions refers to a different object.

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



来源:https://stackoverflow.com/questions/4276794/static-keyword-in-h-file-and-internal-linkage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!