簡體   English   中英

C ++鏈接器錯誤-未內聯定義函數的“未定義引用”

[英]c++ linker error - 'undefined reference' to not inline defined functions

幾天來,我一直在嘗試使用Code :: Blocks IDE(在Linux,Ubuntu 64位)上編譯一個用C ++編寫的項目。 代碼有效,但是存在一些鏈接器錯誤。 我注意到,對於在類中未內聯定義且在其他文件中的函數,我得到了錯誤的“未定義引用”(類是i * .h文件,這些函數的定義位於* .cpp中)。 我試圖編寫自己的Makefile,但沒有幫助。

Makefile文件:

all: project

project: main.o DList.o Person.o
    g++ main.o DList.o Person.o -o project

main.o: main.cpp
    g++ -c main.cpp

DList.o: include/DList.cpp
    g++ -c include/DList.cpp

Person.o: include/Person.cpp
    g++ -c include/Person.cpp

clean:
    rm -rf *.o

盡管我在網上閱讀了一些有關這些錯誤的信息,但我不知道該怎么辦。

//編輯我將Object.cpp和Object.h更改為Person.cpp和Person.h,將* .cpp文件移動到主目錄,並更改了* .cpp文件中的#include路徑。

錯誤:

obj/Debug/main.o||In function `main':|
...main.cpp|19|undefined reference to `DListIterator<Person>::go(int)'|
...main.cpp|20|undefined reference to `std::basic_ostream<char, std::char_traits<char> >& operator<< <Person>(std::basic_ostream<char, std::char_traits<char> >&, DList<Person>&)'|
...main.cpp|21|undefined reference to `DList<Person>::~DList()'|
...main.cpp|21|undefined reference to `DList<Person>::~DList()'|
obj/Debug/main.o||In function `DList<Person>::insert(Person&)':|
...include/DList.h|45|undefined reference to `DList<Person>::insert(Person&, DListIterator<Person>&)'|
||=== Build finished: 5 errors, 0 warnings ===|

如果我在命令行中構建開始make或在Code :: Blocks中使用Build函數,這沒有什么區別。

當我將所有代碼從* .cpp文件復制到* .h文件時,編譯器未返回任何錯誤,因此我認為這只是鏈接器問題。

看來您正在嘗試單獨編譯模板。 通常這是不可能的,因為僅在使用模板時才將其實例化,而在DList.cpp文件中從未使用過該DList.cpp 嘗試以下兩種方法之一:

  • DList中的函數定義移到頭文件中(這是正常的處理方式)。
  • 把一些明確的實例DListDList.cpp文件。 (示例: template class DList<Person>;

問題的完整示例:當前您有:

//DList.h
template<typename T>
class DList {
    void insert(T& newPerson);
    //etc
};

//DList.cpp
#include "DList.h"
//The when this is being compiled, 
//the compiler does not know about Person,
//so it cannot instantiate this function.
template<typename T>
void DList<T>::insert(T& newPerson) {
    //implementation
}
//etc

//main.cpp
#include "DList.h"
#include "Person.h"
int main() {
    //When this is being compiled, it does not know the
    //definition of the out-of-line functions in `DList`,
    //so it cannot instantiate them.
    DList<Person> people;
    people.insert(Person("Joe"));
}

一種可能的解決方法是刪除DList.cpp並將定義放入“ DList.hpp”中:

//DList.hpp
template<typename T>
class DList {
    void insert(T& newPerson) {
        //implementation
    }
    ~DList();
    //etc
};
//the implementations can alternatively be
//placed outside the class, but in the header:
template<typename T>
DList<T>::~DList() {
    //implementation
}

另一個解決方法是顯式實例化DList (在可以使用定義的編譯單元中):

//DList.cpp
#include "DList.h"
#include "Person.h"
template<typename T>
void DList<T>::insert(T& newPerson) {
    //implementation
}
//Explicit instantiation:
template class DList<Person>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM