h关键字和内部链接 [英] static keyword in h file and internal linkage

查看:172
本文介绍了h关键字和内部链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个 static 问题。
我已阅读以下内容:





我仍然无法理解以下行为:
我有一个 h 文件:

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

和两个 cpp 档案:

  // StaticTest1.cpp 
#includeStaticTest.h

int main
return 0;
}

和:

  // StaticTest2.cpp 
#includeStaticTest.h

程序的输出是:

 在A的ctor(1)
在A的ctor 2)
在A的dtor(1)
在A的dtor(0)

现在, A 的构造函数被调用两次,因为 h 文件包含两次,并且由于 A 的实例名为 a 被声明为 static 编译器很高兴。
由于计数器也被声明为static,它也有内部链接,我希望它的值不会在两个 cpp files ---但是程序输出意味着值是共享的,因为它最多可以计数2。



任何见解?



编辑:
关于在 h中声明静态变量的上下文中被认为是良好的编程习惯 code>与 cpp 文件也受欢迎。

解决方案

如果 StaticTest.h 在不同的源文件之间共享,那么你将得到未定义的行为。



类或内联函数,那么它们的定义必须是相同的(相同的标记序列),并且关键的是,任何标识符必须引用相同的实体(除非 const



您违反了这一点,因为计数器有内部链接因此在不同的翻译单元中,函数定义中的标识符指向不同的对象。



参考:C ++ 03 3.2 [basic.def.odr] / p>

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)\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.

解决方案

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.

这篇关于h关键字和内部链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆