2013-06-27 28 views
2

我正在處理大型項目的一小部分。這個項目最初是用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導致編譯錯誤,這顯然是有問題的。

+2

[OT]上面的魔數評論說這不是一個神奇的數字真的很有趣! – yzt

+0

我認爲最好是將類聲明放在上面的代碼中(因爲代碼本身並不顯示它全部在類中)。沒什麼,只是'class'和'public'行和大括號就足夠了。 – yzt

回答

1

我認爲你的問題力量是你忘記在你的CPP文件實際上定義static成員,像這樣:(以Extent.cpp

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

你完全正確。我們最終轉而在'Extent.cpp'中初始化成員,至少,這很有效。 – DYS