C++ 错误“未找到架构x86_64的符号&链接器命令失败,退出代码为1”
抱歉,如果这是一个重复的问题,但我从昨天开始就一直在寻找解决方案,但我还没有发现 我在mac上使用的是CLion,我的编译器来自xcode,所以我觉得它很叮当。任何帮助都将不胜感激!!我需要使用gcc吗?还是我需要修理我的电脑 这里有一条错误消息C++ 错误“未找到架构x86_64的符号&链接器命令失败,退出代码为1”,c++,C++,抱歉,如果这是一个重复的问题,但我从昨天开始就一直在寻找解决方案,但我还没有发现 我在mac上使用的是CLion,我的编译器来自xcode,所以我觉得它很叮当。任何帮助都将不胜感激!!我需要使用gcc吗?还是我需要修理我的电脑 这里有一条错误消息 [ 33%] Linking CXX executable bag Undefined symbols for architecture x86_64: "Bag<int>::add(int)", referenced from:
[ 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
问题不在于编译器或生成系统 这就是模板在C++中的工作方式: 模板代码仅在实例化时编译 因此,您不能将模板函数或类成员分离到单独的cpp文件中,而是必须将所有内容保留在头文件中 请在此阅读最后一段:
@S.M.非常感谢您
#include <iostream>
#include "Bag.h"
int main() {
Bag<int> temp;
temp.add(1);
temp.print();
cout << endl;
return 0;
}
#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
#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] << " ";
}
cmake_minimum_required(VERSION 3.15)
project(bag)
set(CMAKE_CXX_STANDARD 14)
add_executable(bag main.cpp Bag.cpp Bag.h)