C++:具有内部链接的正向声明常量
C++ : forward declaring const with internal linkage
我想转发声明一个常量变量,而不给它外部链接。然而,在我看来,这是不可能的,因为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
$
相关文章:
- 是否可以同时声明一个类成员的常量/非常量?
- 在声明中合并两个常量"std::set"(不是在运行时)
- C++:具有内部链接的正向声明常量
- 为什么不能用常量表达式声明数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 关于静态常量数据模因的声明和定义的混淆
- public:静态常量字符串声明/初始化问题
- 为什么MSVC14允许声明指向动态未初始化常量对象的指针
- 有没有办法声明一个公共静态常量,该常量将使用 constexpr 在源文件中定义(有什么区别)?
- C++ 多态性:如果派生类中的虚函数在基类中声明了常量,是否需要将其声明为常量
- C++ 声明常量变量,但推迟其初始化?
- 如何在类中声明常量size_t
- 为什么我可以使用类型别名声明常量引用
- 如何在头文件中声明常量对
- 为什么我不能声明常量数组?(不是常量数组,而是数组,其元素和大小无法更改)
- 如何在类中使用常量类变量声明常量数组
- 在c++中声明常量时,对宽字符串使用value of string
- 在哪里声明常量结构数组
- 如何正确声明常量表达式
- 使用#define声明常量的好处是什么?