【发布时间】:2020-01-21 17:42:13
【问题描述】:
我知道全局是不好的,但作为一种实践,这是初始化在多个目标文件之间使用的全局类的正确方法吗?
标题 1.h
class test {
int id;
public:
test(int in){
id = in;
}
int getId(){
return id;
}
};
extern test t;
文件 1.cc:
#include <iostream>
#include "1.h"
int main(){
std::cout << t.getId() << std::endl;
return 0;
}
文件 2.cc:
#include "1.h"
test t(5);
现在,如果我在标题中全局使用static 方法而不是extern,该怎么办?
如果我错了,请纠正我,但编译得很好,但是我会在目标文件和最终二进制文件中拥有相同 t 的 2 个不同的不相关副本?那不好吗?还是链接器会对其进行排序以消除多个副本?
【问题讨论】:
-
当心static initialization order fiasco。还阅读了 ODR(一个定义规则)。另见isocpp.org/wiki/faq/ctors#static-init-order
-
为什么头文件中有extern声明?
-
extern 总是在标题中。
-
@MosheRabaev 避免违反 ODR。
-
你确定这是正确的吗?在你需要的地方使用 extern 更有意义,它更清楚,因为通过查看 main 我不知道 t 是在哪里定义的
标签: c++ static initialization one-definition-rule