c++ 中目录中文件的未定义引用错误

An undefined reference error for files in a directory in c++

本文关键字:未定义 引用 错误 文件 中文 c++      更新时间:2023-10-16

我正在做一个项目,在项目内部,我将自己的类和函数分离到一个名为base_lib的目录中。编译项目时,我不断收到此库中某个类的未定义引用错误。我一直试图在许多不同的论坛上找到答案,最终决定自己问。代码:

堆栈.h

#ifndef __STACK_H
#define __STACK_H

namespace stacker
{
/*******
My code here
*******/
}

#endif

堆栈.cpp

#include "stack.h"
#include <iostream>
using namespace std;
template <typename var>
stacker::Stack<var>::Stack()
{
head = nullptr;
tail = nullptr;
}

修复.h

#ifndef __FIX_H
#define __FIX_H
#include <iostream>
#include <string>

namespace fixes
{
/*******
My code here
*******/
}
#endif

修复.cpp

#include "fix.h"
#include "base_lib/stack.h"
#include <iostream>
#include <string>

using namespace std;
using namespace stacker;

主.cpp

#include <iostream>
#include "fix.h"
#include "base_lib/functions.h"
using namespace fixes;
using namespace mine;
using namespace std;

编译器错误

C:...:fix.cpp:(.text+0xa2): undefined reference to `stacker::Stack<char>::Stack()'
...

有人有任何提示或技巧吗?

您似乎在C++文件中有一个模板,而不是头文件。

这意味着模板将无法编译,因此您会收到错误。

在这里阅读:为什么模板只能在头文件中实现?