标头中的结构数组出现链接器错误

Linker error with array of structs in header

本文关键字:链接 错误 数组 结构      更新时间:2023-10-16

我正在处理一个大型项目的一小部分。该项目最初是用C编写的,大约6年前过渡到C++(我第一次听说这个项目大约是在3周前…)

一切都很顺利。我遇到的错误来自链接器:

libBlah.so.0.0: undefined reference to `Extent::structArray'
collect2: error: ld returned 1 exit status

错误发生在它尝试首先链接的任何可执行文件上;存在少数可执行文件,每个可执行文件取决于Extent类和structArray数据成员。在尝试(但失败)链接其他可执行文件之前,它成功地链接了整个libBlah库。

Extent.hpp中,在Extent类声明的public部分中,structArray被声明(并被巧妙地初始化),因此:

struct structThing
{
    const char *name;
    int compress_flag;
    bool (*func1)( byte*, int32, ByteArray&, int );
    bool (*func2)( byte*, byte*, int32, int32& );
};
// This isn't actually a magic number
static const int num_things = 7;
static structThing structArray[ num_things ];
struct structArray_init
{
    structArray_init()
    {
        structThing init[] =
        {
            { "none", 0, NULL, NULL },
            { "thingA", 1, funca1, funca2 },
            { "thingB", 2, funcb1, funcb2 },
            { "thingC", 4, funcc1, funcc2 },
            { "thingD", 8, funcd1, funcd2 },
            { "thingE", 16, funce1, funce2 },
            { "thingF", 32, funcf1, funcf2 }
        };
        for( int i = 0 ; i < num_things ; ++i )
        {
            structArray[i] = init[i];
        }
    }
};
static structArray_init thingy_init;

所有12个函数(funca1到funcf2)都是Extent的静态函数,稍后在标头的公共部分中声明。

该构建由CMake管理。基本上,在CMake中,每个独立的依赖程序都被赋予整个libBlah库作为依赖。我试着摆弄链接顺序,但没有用。

在此链接器错误之前,我在Extent的非静态函数中初始化structArray时出现编译错误,这显然是有问题的。

我认为您的问题可能是您忘记在CPP文件中实际定义static成员,如下所示:(在Extent.cpp中)

Extent::structThing Extent::structArray [Extent::num_things];
Extent::structArray_init Extent::thingy_init;