未定义的架构符号 x86_64 C ++中的错误,标头显然未链接

Undefined symbols for architecture x86_64 error in c++, header apparently isn't linked

本文关键字:错误 链接 符号 x86 未定义      更新时间:2023-10-16

嗨,我在c++方面遇到了一些问题,当我试图编译我的3个文件main.cpp、my_Stack.cpp和my_Stack.hpp时,我得到了"架构x86_64的未定义符号"错误,就好像我没有包括头文件一样,如果我在main.cpp中添加"#include"my_Stack.chpp"而不是"#include"my_Steak.hpp",效果很好。


//main.cpp
#include <iostream>
#include "My_Stack.hpp"
int main(int argc, const char * argv[]) {
My_Stack<int> s = My_Stack<int>();
s.push(1);
s.push(2);
cout << s.pop() << endl;
cout << s.pop() << endl;

}

//My_Stack.hpp
#ifndef My_Stack_hpp
#define My_Stack_hpp
#include <stdio.h>
#include <string>
using namespace std;
template<class T>
class My_Stack {
public:
My_Stack();
void push(T v);
T pop();
private:
class My_Stack_Node {
public:
T data;
My_Stack_Node* next;
My_Stack_Node(T n) {
data = n;
next = NULL;
}
};
My_Stack_Node* head;
};

#endif /* My_Stack_hpp */

//My_Stack.cpp
#include "My_Stack.hpp"
#include <string>
#include <sstream>
using namespace std;
template<class T>
My_Stack<T>::My_Stack() {
this->head = NULL;
}
template<class T>
void My_Stack<T>::push(T v) {
if (this->head == NULL) {
this->head = new My_Stack_Node(v);
}
else {
My_Stack_Node* aux = new My_Stack_Node(v);
aux->next = this->head;
this->head = aux;
}
}
template<class T>
T My_Stack<T>::pop() {
My_Stack_Node* aux = this->head;
this->head = this->head->next;
return aux->data;
}

模板定义必须放入相应的头文件中,即My_Stack.cpp中的定义必须放入My_Stack.hpp中。

建议您查看常见问题:
https://isocpp.org/wiki/faq/templates#separate-来自decl 的模板fn defn

从常见问题粘贴相关部件:

模板不是类或函数。模板是一种"模式"编译器用于生成类族或功能

为了让编译器生成代码,它必须同时看到模板定义(而不仅仅是声明)和用于"填充"模板的特定类型/任何内容。对于例如,如果您试图使用Foo,编译器必须看到Foo模板和您试图制作特定Foo

您的编译器可能不记得了一个.cpp文件在编译另一个.cpp文件时的详细信息。它可以,但大多数人没有,如果你正在阅读这个常见问题解答,它几乎绝对不会。顺便说一句,这被称为"单独编译"模型。">

相关文章: