3

我有 2 个字符串数组,它们在头文件中定义,如下所示:

#ifndef DRC_DefinesH
#define DRC_DefinesH
#include <string>
#include <System.hpp>
//---------------------------------------------------------------------------

std::string MagFields[] = {
   "SCAN", "EVENT", "EVENT2", "EVENT1", "EVENT3", "VECTORX", "VECTORY", "VECTORZ", "MAG1RAW", "MAG2RAW", "MAG3RAW",
   "MAG4RAW", "MAG1UNCOMP", "MAG2UNCOMP", "MAG3UNCOMP", "MAG4UNCOMP", "MAG1COMP", "MAG2COMP", "MAG3COMP", "MAG4COMP",
   "GRAD1", "GRAD2", "GRAD3", "UTC", "LAT", "LON", "ALT", "ANALOG1", "ANALOG2", "ANALOG3", "ANALOG4", "SYSTIME"};

std::string AnalogFields[] = {
   "SCAN", "EVENT0", "EVENT1", "EVENT2", "EVENT3", "ANALOG1", "ANALOG2", "ANALOG3", "ANALOG4", "ANALOG5", "ANALOG6",
   "ANALOG7", "ANALOG8", "ANALOG9", "ANALOG10", "ANALOG11", "ANALOG12", "ANALOG13", "ANALOG14", "ANALOG15", "ANALOG16",
   "ANALOG17", "ANALOG18", "ANALOG19", "ANALOG20", "ANALOG21", "ANALOG22", "ANALOG23", "ANALOG24", "ANALOG25",
   "ANALOG26", "ANALOG27", "ANALOG28", "ANALOG29", "ANALOG30", "ANALOG31", "ANALOG32"};

... other stuff

    #endif

此标头包含许多其他内容,并且间接包含在 C++ Builder XE2 项目的每个单元中。当我构建项目时,我收到很多链接器警告,指出

"public symbol _MagFields and _AnalogFields are defined in both modules AAA and BBB"

其中 AAA 和 BBB 依次是项目中的每个单元组合。

这些特定的声明可以移动到一个单元的实现端并且警告消失,但我想了解为什么它是必要的。Embarcadero 文档只是告诉我如何摆脱警告,而不是它的含义。

4

1 回答 1

7

您在标题中定义数组,在包含标题的每个翻译单元中给出定义。但是你只允许一个定义,因为定义是导致为数组分配内存的原因,它只能存在于一个地方。这就是所谓的单一定义规则

将定义移动到源文件中,这样它们就不会重复。然后只需在标头中声明数组:

extern std::string MagFields[];
extern std::string AnalogFields[];

如果您不需要修改它们,另一种选择是声明它们const以赋予它们内部链接,以便包含定义的每个翻译单元都获得自己的数组副本。这样做的缺点是您最终会在程序中使用多个数组副本,从而浪费内存。

于 2013-11-08T16:40:22.767 回答