链接在代码块中不起作用!?(未定义的引用...

Linking doesn't work in codeblocks!? (undefined reference to ...)

本文关键字:未定义 引用 不起作用 代码 链接      更新时间:2023-10-16

我对代码块版本 10.05 有问题。我做了一个 c++ 项目,我写了一个这样的程序:

主.cpp

#include <iostream>
#include "vectorddd.hpp"

using namespace std;
int main()
{
    vector3D<int> tesztinttomb;
    tesztinttomb.saveout("igen.dat");
    return 0;
}

头文件 (vectorddd.hpp):

#ifndef VECTORDDD_HPP_INCLUDED
#define VECTORDDD_HPP_INCLUDED
#include <iostream>
template <class T>
class vector3D  {
    T *x;
    T *y;
    T *z;
    int meret;
public:
    void saveout(char* FileName);
    vector3D(int Meret=0) :  x(new T[meret]), y(new T[Meret]), z(new T[Meret]), meret(Meret) {}
    ~vector3D()  { delete [] x; delete [] y; delete [] z; }
};

#endif // VECTORDDD_HPP_INCLUDED

实现文件 (vectorDDD.cpp):

#include "vectorddd.hpp"
template <class T>
void vector3D<T>::saveout(char* FileName) {
    int i=0;// I know this is stupid... but the emphasis is on the linking problem
}

它只是没有链接在一起。我知道我必须在属性>构建选项中检查.cpp文件链接和编译设置。而且我没有发现任何问题,只是写得总是一样:

In function `main':
undefined reference to `vector3D<int>::saveout(char*)'
||=== Build finished: 1 errors, 0 warnings ===|

如果我将.cpp文件实现放入我的 .hpp 文件中,它可以正常工作。但这不是代码块应该如何工作。

您的模板需要位于头文件中,请考虑一下,如果模板在 cpp 文件中,如何实例化模板?

你应该把这个:

template <class T>
void vector3D<T>::saveout(char* FileName) {
    int i=0;// I know this is stupid... but the emphasis is on the linking problem
}

在您的标头 vectorddd.hpp 文件中

请参阅类似的 SO 帖子:C++在 .CPP 文件