c++ - 错误“未找到体系结构 x86_64 和链接器命令的符号失败,退出代码为 1”
问题描述
对不起,如果这是一个重复的问题,但我从昨天开始一直在寻找解决方案,但我还没有找到..
我在mac上使用CLion,我的编译器来自xcode,所以我认为它是clang。任何帮助,将不胜感激!!我需要使用 gcc 吗?还是我需要修复我的cmake?
这是一条错误消息。
[ 33%] Linking CXX executable bag
Undefined symbols for architecture x86_64:
"Bag<int>::add(int)", referenced from:
_main in main.cpp.o
"Bag<int>::print()", referenced from:
_main in main.cpp.o
"Bag<int>::Bag()", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [bag] Error 1
make[2]: *** [CMakeFiles/bag.dir/all] Error 2
make[1]: *** [CMakeFiles/bag.dir/rule] Error 2
make: *** [bag] Error 2
这是main.cpp
#include <iostream>
#include "Bag.h"
int main() {
Bag<int> temp;
temp.add(1);
temp.print();
cout << endl;
return 0;
}
这是 Bag.h。
#ifndef BAG_BAG_H
#define BAG_BAG_H
#include <vector>
#include <cstdlib>
#include <iostream>
using namespace std;
static const size_t CAPACITY = 100;
template <class T>
class Bag{
public:
Bag();
size_t size() const;
bool empty();
bool check(const T& item);
void resize(size_t new_size);
void clear();
void remove(const T& item);
void add(T item);
void print();
private:
T* data;
size_t _size;
};
#endif //BAG_BAG_H
这是 Bag.cpp。
#include "Bag.h"
template <class T>
Bag<T>::Bag() : data{new T[CAPACITY]}, _size{0} {}
template <class T>
size_t Bag<T>::size() const {return _size;}
template <class T>
bool Bag<T>::empty() {
}
template <class T>
bool Bag<T>::check(const T &item) {
}
template <class T>
void Bag<T>::resize(size_t new_size) {
T* temp = new T[new_size];
for(int i = 0; i == _size; i++)
*data++ = *temp++;
delete [] data;
this->data = &temp;
}
template <class T>
void Bag<T>::add(T item) {
data[_size + 1] = item;
_size++;
}
template <class T>
void Bag<T>::print() {
for(int i = 0; i == _size; i++)
cout << data[i] << " ";
}
这是 CMakeLists.txt
cmake_minimum_required(VERSION 3.15)
project(bag)
set(CMAKE_CXX_STANDARD 14)
add_executable(bag main.cpp Bag.cpp Bag.h)
解决方案
问题不在于您的编译器或制作系统。
这就是模板在 C++ 中的工作方式:模板代码仅在实例化时编译。
因此,您不能将模板函数(或类成员)分离到单独的 cpp 文件中,而必须将所有内容保留在头文件中。
在此处阅读最后一段: http ://www.cplusplus.com/doc/oldtutorial/templates/
推荐阅读
- selenium-webdriver - 如何为与类和 aria-label 绑定在 td 内的日历元素编写 xpath
- java - 升级 junrar 时的警告:不推荐使用符号 extractArchive
- amazon-web-services - 无法在 AWS cloud9 中为赛普拉斯安装依赖项
- python-3.x - 获取列表中所有项目的组合,同时禁止某些项目放在一起
- android - 工具栏不出现
- time-series - 如何在 kdb+/q 中为每个新行触发更新?
- vb.net - Vb.net 控件从创建于它之外的线程访问
- authentication - 使用不透明的访问令牌会使我的服务器有状态吗?
- java - 使用套接字从 PHP Web 应用程序控制 Java 应用程序
- powershell - 如何查看 BizTalk 发送端口中的传输类型配置(例如 Bindings.xml 的内容)?