C++ : forward declaring const with internal linkage

标签 c++ constants extern linkage

我想转发声明一个 const 变量而不给它外部链接。然而,在我看来,这是不可能的,因为 extern 关键字同时意味着“这具有外部链接”和“这是一个变量声明,而不是定义”,而我无法得到一个没有其他:

//// main.cpp: ////

extern const char table[256];    // forward declaration. External linkage.
// const char table[256];        // Error: table requires an initializer
// static const char table[256]; // Same error

// foo uses table so I need it forward declared:
char foo()
{
    // uses table
}

const char table[256] = {...}; // Actual definition

我的理解正确吗?有什么解决办法吗?

最佳答案

首先,前向声明仅为类型定义。您可以输入

class X;

然后使用 X * 为例。

您在这里想要实现的目标是在实际使用之前声明符号。 我知道执行此操作的唯一方法是通过 extern 关键字。

但是如果想让符号链接(symbolic link)成为内部的,匿名命名空间可以提供帮助

namespace {
extern const char table[256]; // symbol declaration. Internal linkage.
}

char foo() {
    // use table
}
namespace {
const char table[256] = {...}; // symbol definition. Internal linkage.
}

这是您可以做的测试

$ cat test.cc
extern const char moo[4];
char foo() { return moo[2]; }
const char moo[4] = {0};
$ g++  -c test.cc -o test.o -O3 && g++ test.o -shared -o test.so && nm -gD test.so | grep moo
00000000000005ad R moo
$
$ cat test.cc
namespace {
    extern const char moo[4];
}
char foo() { return moo[2]; }
namespace {
    const char moo[4] = {0};
}
$ g++  -c test.cc -o test.o -O3 && g++ test.o -shared -o test.so && nm -gD test.so | grep moo
$

关于C++ : forward declaring const with internal linkage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60267490/

相关文章:

java - 如何从Java中的其他类初始化静态最终变量

objective-c - 尝试实现 MIDIReceived 但我不知道结果发送到哪里

android - 使用 FFMPEG 压缩视频

c++ - C++ 中的 Java HashSet 等价物

c++ - 避免到处都有静态常量变量

c++ - const void 有什么意义?

c - 为什么此代码不生成重新声明错误?

c++ extern constant int 用于数组大小

c++ - 一些比普通循环和设置更快地分配和初始化数组的方法

c++ - 是否可以将两种字符集放在同一个文件中