C++:具有内部链接的正向声明常量

C++ : forward declaring const with internal linkage

本文关键字:声明 常量 链接 内部 C++      更新时间:2023-10-16

我想转发声明一个常量变量,而不给它外部链接。然而,在我看来,这是不可能的,因为extern关键字同时意味着"这是一个外部链接"answers"这是变量声明,而不是定义",而且我不能没有另一个:

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

然后使用例如CCD_ 2。

您在这里试图实现的是,在实际使用之前声明符号。我知道的唯一方法是通过extern关键字。

但是,如果想使符号链接内部化,匿名命名空间可以帮助

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
$