[英]Extern variable undefined
我面臨外部變量聲明的問題。 我有一堆包含結構定義的.cpp文件:
const System SystemA = {"A", 1, 2 ...}; //In A.cpp
const System SystemB = {"B", 1, 2 ...}; //In B.cpp
...
這些Cpp文件只是作為一種簡單的方法添加到服務器,以添加新的結構,並輕松查找一個特定的結構定義。 (因為我可能有100個定義,並且每個定義都是多[50]行代碼)。
當我嘗試在另一個編譯單元(.cpp)中使用它們時:
extern const System SystemA;
extern const System SystemB;
...
void InitStructs(){
SystemA.Init();
SystemB.Init();
...
}
我只是得到undefined reference to SystemA
undefined reference to SystemB
,依此類推。 我正在執行此統一初始化,因為在每個system.cpp中,我都將初始化作為靜態動態初始化進行。 但這是有風險的,因為不能確保初始化順序(靜態初始化順序失敗)。 因此,我得到分段錯誤,具體取決於cpp編譯順序。
我朝着這種方法邁進,但現在它甚至無法編譯...。有什么幫助嗎?
SystemA
和SystemB
應該使用extern
關鍵字定義:
extern const System SystemA = {"A", 1, 2 ...}; //In A.cpp
extern const System SystemB = {"B", 1, 2 ...}; //In B.cpp
或者,您可以創建一個標題,例如Globals.h
,聲明它們:
extern const System SystemA;
extern const System SystemB;
這樣可以確保它們在所有包含標頭的編譯單元之間具有相同的鏈接。 稍后,您可以不使用extern
關鍵字定義它們,因為extern
聲明已經可見:
丙型肝炎
#include "Globals.h"
const System SystemA = {"A", 1, 2 ...};
丙型肝炎
#include "Globals.h"
const System SystemB = {"B", 1, 2 ...};
在C ++中,默認情況下,全局范圍內的const
對象也是static
,即,它們在源文件外部不可見。 要解決此問題,請將extern
添加到每個定義中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.