我想转发声明一个 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/