对常量数组的未定义引用 [英] undefined reference to array of constants

查看:185
本文介绍了对常量数组的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a.cpp

const unsigned char whatever[123] = { /* ... */ };

ah

extern const unsigned char whatever[123];



b.cpp

b.cpp

#include "a.h"
unsigned char x = whatever[0];
// error: undefined reference to 'whatever'

为什么我得到一个未定义的引用错误?如果没有 const ,错误消失。

Why do I get an undefined reference error? Without the const, the error goes away.

如何在多个翻译单元之间共享一组常量?

How do I share an array of constants among multiple translation units?

推荐答案

这是人们遇到的一个怪癖,它只是一个你定义了一个ah头文件的事情,一个123个字符的常量数组,并为其分配外部链接。当它被包含到b.cpp文件中时,你基本上有希望在其他翻译单元中找到编译器。

This is one of the quirks people run into, it's simply a matter that you've defined an a.h header file which declares a const array of 123 chars, and assigned it external linkage. When it is included into the b.cpp file, you're basically promising the compiler it's going to find in some other translation unit.

但是,每个 const 变量有一个黑暗的秘密 - 它被困在其定义的翻译单元中,因为它隐含地给了静态链接。您承诺您的编译器不管将在多个翻译单元之间共享,但实际上它只忠于一个翻译单元,并且不希望被共享。而且,你知道其余的。

But, every const variable has a dark secret - it's trapped inside its defining translation unit because it is implicitly given static linkage. You promised your compiler whatever will be shared across multiple translation units, but it is actually loyal to just one translation unit and doesn't like to be shared. And, well, you know the rest.

通过在实现文件中明确声明 extern 来解决。

Resolve by explicitly stating extern in the implementation file.

这篇关于对常量数组的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆