简体   繁体   English

外部“C”与const

[英]extern “C” with const

We have a piece of C-code in our system which contains a few arrays like this with global access: 我们的系统中有一段C代码,其中包含一些具有全局访问权限的数组:

source.h source.h

extern const int magic[5];

source.c: 由source.c:

const int magic[] = { 1, 2, 3, 4, 5};

Somebody decided it would be a good idea to change this to C++ and so the above ended up in an extern "C" block: 有人认为将此更改为C ++是一个好主意,因此上述内容最终出现在extern "C"块中:

source.h: source.h:

extern "C" { 
    const int magic[5]; 
}

source.cc: source.cc:

extern "C" {
    const int magic[] = { 1, 2, 3, 4, 5};
}

This compiled without a squeak with gcc -Wall 编译时没有使用gcc -Wall发出吱吱声

It wasn't until someone tried to use that array that we discovered the problem. 直到有人试图使用该阵列我们发现了问题。 using const inside an extern "C" causes no external symbol to be generated at all. extern "C"使用const会导致根本不生成外部符号。 This happens with gcc, sun workshop and ibm's compiler. 这发生在gcc,sun workshop和ibm的编译器上。

I'm somewhat at a loss as to whether or not this is expected behaviour, given that gcc doesn't warn you that you're doing something odd. 考虑到gcc没有警告你,你做的事情很奇怪,我有点不知道这是否是预期的行为。

So is this behaviour for this specified by the standard, or is it a rather pervasive bug? 这个标准所规定的行为也是如此,还是一个相当普遍的错误?

const variables have internal linkage (as if declared static ) unless you use extern to specify external linkage. const变量具有内部链接(如果声明为static ),除非您使用extern指定外部链接。 You'll need external linkage if you want to define it in one source file and access it from others. 如果要在一个源文件中定义它并从其他源文件访问它,则需要外部链接。

That's in addition to using extern "C" to specify the language linkage. 除了使用extern "C"指定语言链接之外。

extern "C" { 
    extern const int magic[5]; 
}

Your C declaration correctly specified external linkage; 您的C声明正确指定了外部链接; but you removed it when you changed to C++. 但是当你改为C ++时你删除了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM