[英]Linker error when including header in files other than main.cpp
我試圖以某種方式將一些實用程序函數和全局變量添加到我的代碼中,以便可以在我項目中想要的每個類中使用它們。 我想將.hpp文件用於定義,而將.cpp文件用於實現。
這是這兩個文件的摘要:
// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp
namespace utils {
int global_variable1;
int global_variable2;
void utility_function1(...);
void utility_function2(...);
void utility_function3(...);
}
#endif /* utilities_hpp */
和實現:
// This is Utilities.cpp
#include "Utilities.hpp"
namespace utils {
void utility_function1(...) {
// Some code
}
void utility_function2(...) {
// Some code
}
void utility_function3(...) {
// Some code
}
}
除了我的main.cpp
文件外,我還有另外兩個類。 我的main.cpp
文件包含Class1.hpp
標頭,其中包含Class2.hpp
標頭。
現在,我認為我可以在Class1.hpp
或Class2.hpp
放入另一個#include "Utilities.hpp"
,而不會出現任何問題,因為我已經在該標頭中使用了防護措施。 問題是,當我嘗試執行此操作時,鏈接器將向我拋出此錯誤: Apple Mach-O Linker (ld) Error Group - clang: error: linker command failed with exit code 1 (use -v to see invocation)
,我可以不知道為什么或做什么來解決它。
我在macOS Sierra 10.12.4上使用Xcode 8.3。
我希望我能夠解釋我的問題,非常感謝。
您在標頭中的全局變量上缺少extern
關鍵字。 結果,您正在定義它們,當您將標頭包含在兩個不同的源模塊中時,將導致多個定義。
在將extern
添加到頭文件( extern int global_variable1;
)中之后,您需要在.cpp文件中添加定義,並在其中定義函數。
您違反了一個定義規則。 應該在標頭global_variable1
和global_variable2
聲明為extern
,並在一個轉換單元(可能是Utilities.cpp)中進行定義。
您已經在包含在多個轉換單元中的標頭中定義了全局變量,因此在main.cpp中定義了一個utils::global_variable1
,在Utilities.cpp中定義了一個。 當涉及鏈接時間時,鏈接器無法知道要使用哪個global_variable1
,因此會引發錯誤。
要解決此問題,請將extern
關鍵字添加到聲明中,然后在“ Utilities.cpp”中添加定義:
Utilities.hpp:
// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp
namespace utils {
extern int global_variable1;
//^^^^^^ <-----HERE
extern int global_variable2;
//^^^^^^ <-----HERE
void utility_function1(...);
void utility_function2(...);
void utility_function3(...);
}
#endif /* utilities_hpp */
Utilities.cpp:
// This is Utilities.cpp
#include "Utilities.hpp"
namespace utils {
int global_variable1; //<---- Definitions added
int global_variable2;
void utility_function1(...) {
// Some code
}
void utility_function2(...) {
// Some code
}
void utility_function3(...) {
// Some code
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.