Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

c++ - static keyword in h file and internal linkage

Yet another static question. I have read the following:

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)
", counter);
    }
    ~A () {
        counter--;
        printf("In A's dtor(%d)
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...