当我的代码位于单独的文件中时,我很难运行它们。当我将它们全部放在main.cc中时,它就可以正常工作。
我正在使用VS Code Runner或G ++在带有G ++ 7.3.0-27ubuntu1〜18.04的Ubuntu 18.04上运行此程序。
当我尝试仅通过函数而不通过类链接test.cc和test.h文件时,此方法工作正常:
test.h
#include <iostream>
void test();
test.cc
#include "test.h"
void test()
{
std::cout << "Test\n";
}
main.cc
#include <iostream>
#include "test.h"
int main() {
test();
return 0;
}
但是当我尝试运行以下命令时,它不起作用:
main.cc
#include <iostream>
#include "singly_linked_list.h"
int main() {
SinglyLinkedList<int> list;
list.Push(1);
std::cout << list.Top() << "\n";
return 0;
}
singly_linked_list.h
#ifndef SINGLY_LINKED_LIST_H
#define SINGLY_LINKED_LIST_H
#include <cstddef>
template <typename T>
struct Node
{
T data;
Node<T> *next;
};
template <typename T>
class SinglyLinkedList
{
private:
Node<T> * head_;
std::size_t size_;
public:
SinglyLinkedList()
{
this->head_ = NULL;
this->size_ = 0;
}
// push
void Push(T data);
// insert
// delete
// clear
// length
// get_nth
// get_nth_from_last
// get_middle
// top
T Top();
};
#endif
singly_linked_list.cc
#include "singly_linked_list.h"
template <typename T>
void SinglyLinkedList<T>::Push(T data)
{
Node<T> * temp = new Node<T>;
temp->data = data;
this->size_++;
if( this->head_ == NULL )
{
this->head_ = temp;
this->head_->next = NULL;
}
else
{
temp->next = this->head_->next;
this->head_ = temp;
}
}
template <typename T>
T SinglyLinkedList<T>::Top()
{
if( this->head_ == NULL )
{
throw ("List is empty");
}
else
{
return this->head_->data;
}
}
在VS Code Runner上,出现此错误:
[Running] cd "/home/mikko/workspace/review/data_structures/linked_list_singly/" && g++ main.cpp -o main && "/home/mikko/workspace/review/data_structures/linked_list_singly/"main
/tmp/ccT13cfO.o: In function `main':
main.cpp:(.text+0x30): undefined reference to `SinglyLinkedList<int>::Push(int)'
main.cpp:(.text+0x3c): undefined reference to `SinglyLinkedList<int>::Top()'
collect2: error: ld returned 1 exit status
[Done] exited with code=1 in 0.269 seconds
当我使用G ++编译时
g++ main.cc singly_linked_list.cc -o list
/tmp/ccqF3LJY.o: In function `main':
main.cc:(.text+0x30): undefined reference to `SinglyLinkedList<int>::Push(int)'
main.cc:(.text+0x3c): undefined reference to `SinglyLinkedList<int>::Top()'
collect2: error: ld returned 1 exit status
如果我将所有内容都放入main.cc并从那里进行编译,则此代码有效,但我希望将其保存在单独的文件中。