C++:使用内部链接向前声明 const

Fra*_*oVS 6 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
Run Code Online (Sandbox Code Playgroud)

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

Tar*_*ran 0

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

class X;
Run Code Online (Sandbox Code Playgroud)

然后使用X *例如。

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

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

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

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

这是您可以做的测试

$ 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
$
Run Code Online (Sandbox Code Playgroud)
$ 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
$
Run Code Online (Sandbox Code Playgroud)

  • @MarekR 该示例表明该变量不在头文件中。另外,问题说需要内部链接或不需要链接,如果在头文件中,这总是会导致该问题。 (3认同)