我正在處理大型項目的一小部分。這個項目最初是用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
被聲明(和hackily初始化)從而:
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(通過funcf2 funca1)是Extent
靜態函數,稍後在標題的公共部分宣佈。
構建由CMake管理。基本上,在CMake中,每個獨立的相關程序都被賦予整個libBlah
庫作爲依賴項。我嘗試過使用鏈接命令,但無濟於事。
在此鏈接器錯誤之前,我在Extent
的非靜態函數中初始化structArray
導致編譯錯誤,這顯然是有問題的。
[OT]上面的魔數評論說這不是一個神奇的數字真的很有趣! – yzt
我認爲最好是將類聲明放在上面的代碼中(因爲代碼本身並不顯示它全部在類中)。沒什麼,只是'class'和'public'行和大括號就足夠了。 – yzt