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

C++ C++;:具有内部链接的前向声明常量,c++,constants,extern,linkage,C++,Constants,Extern,Linkage,我想向前声明一个常量变量,而不给它外部链接。然而,在我看来,这是不可能的,因为extern关键字同时表示“this has external linkage”和“this is a variable declaration,not a definition”,而我不能没有另一个: //// main.cpp: //// extern const char table[256]; // forward declaration. External linkage. // const char

我想向前声明一个常量变量,而不给它外部链接。然而,在我看来,这是不可能的,因为
extern
关键字同时表示“this has external linkage”和“this is a variable declaration,not a definition”,而我不能没有另一个:

//// 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
关键字

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

这是一个你可以做的测试

$ 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
$

@JesperJuhl以及如何在没有初始化的情况下对常量数组进行正向声明?无论如何,拥有这样的全局数组可能不是一个好主意,而是将其传递给“foo”并使用std。。foo(std::array&table)匿名名称空间仅在单个翻译单元中生成场景。当他希望使用头文件在cpp之间共享实例时,匿名名称空间将导致实例的重复。对于普通创建的类型,这不是问题,因为链接器将清理它。您的版本应该会导致链接问题。我认为任何不是定义的声明,如
void func()
外部整数计数
可以被视为向前声明。@MarekR该示例表明该变量不在头文件中。另外,问题是需要内部链接或不需要链接,如果在头文件中,这总是会导致该问题。
$ 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
$