【问题标题】:linkage of c++ const globals?c ++ const全局变量的链接?
【发布时间】:2019-01-05 17:21:23
【问题描述】:

我有 5 个文件: 啊:

extern const int a;

a.cpp:

#include "a.h"
const int a = 1;

b.h:

extern const int a;
extern const int b;

b.cpp:

#include "b.h"
const int b = a + 1;

main.cpp:

#include <stdio.h>
#include "a.h"
#include "b.h"
int c = a + 1;
int d = b + 1;
int main() {
  printf("c: %d\n", c);
  printf("d: %d\n", d);
  return 0;
}

我按照以下顺序编译它们:

gcc -c *.cpp
gcc a.o b.o main.o -o after
gcc main.o a.o b.o -o before

当我运行afterbefore 时:

./after
c: 2
d: 3

./before
c: 2
d: 1

其他人可以解释这些全局变量的联系吗?

【问题讨论】:

  • 不使用全局变量的一个很好的论据。

标签: c++ linkage


【解决方案1】:

默认情况下,全局 const 具有内部链接,但您已使用 extern 声明将其无效,因此 ab 具有您想要的外部链接。 (如果他们不这样做,您的程序就不会链接!)

但是,由于the static initialisation order fiasco,您不知道这些常量的初始化顺序是什么。当然,它们在翻译单元中是自上而下的,但跨翻译单元所有赌注关闭。您可以通过更改链接顺序来观察其中一些恶作剧。

尽量避免这样的代码; various approaches exist 为您重新设计。

【讨论】:

  • 如果 OP 的实变量是内置类型,并且用简单的字面量初始化,那么简单的解决方法是在 a.h 中写入 const int a = 1; 然后 bh 是 #include "a.h"const int b = a+1; - 当然可悲的是,OP 可能已经将一个复杂的问题缩减到了它的本质(我将对其进行投票)。
  • @MartinBonner 确实
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多