简体   繁体   English

在C ++标头中声明大数组

[英]Declaring large array in C++ header

It's been ages since I last worked with C++. 自从我上一次使用C ++以来已经有很多年了。

Situation: I have a large array that needs to be available in different .cpp files. 情况:我有一个很大的阵列,需要在不同的.cpp文件中可用。 It is immutable, so I thought I better put a const char array[] = … in the header file. 它是不可变的,所以我认为最好将const char array[] = …放在头文件中。 But now the array appears several times in the compiled binary, as far as I can see. 但是据我所知,数组现在在已编译的二进制文件中出现了几次。

What is the proper way to declare large constant arrays in a header, so they won't be compiled into every source object? 在标头中声明大常量数组的正确方法是什么,这样它们就不会被编译到每个源对象中?

If you define an array in a header file (whether or not you initialise it), you will get lots of copies. 如果在头文件中定义数组(无论是否初始化),都会得到很多副本。

You want to declare it in the header: 您想在标题中声明它:

extern const char array[];

and define it like this in your .c / .cpp file: 并在.c / .cpp文件中定义如下:

const char array[] = ... ;

Use the header guard in header file. 在头文件中使用头保护。 So it prevent from multiple declaration. 因此,它避免了多重声明。 eg. 例如。

#ifndef HEADER_H
#define HEADER_H
const char array[] = …
.
.
#endif //HEADER_H

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

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