簡體   English   中英

架構x86_64 C ++的未定義符號

[英]Undefined symbols for architecture x86_64 c++

我正在嘗試在C ++中創建一個自定義'Matrix'類,並且遇到了我無法理解的“體系結構x86_64的未定義符號:”錯誤。 我的相關代碼是-

HEADER

#ifndef CORE_H
#define CORE_H
#include <stdint.h>

class Size
{
public:
    Size(const uint64_t nrows, const uint64_t ncols, const uint64_t nframes);

    uint64_t rows;
    uint64_t cols;
    uint64_t frames;
};

template <typename T>
class Matrix
{
public:
    Matrix(const uint64_t rows, const uint64_t cols, const uint64_t frames);
    Matrix(const uint64_t rows, const uint64_t cols, const uint64_t frames, T *data);

    void print();

private:
    Size sz;
    T *_data;
};

#endif //CORE_H

資源

#include <string.h>
#include <cstdlib>
#include <stdio.h>

#include "core.h"

Size::Size(const uint64_t nrows, const uint64_t ncols, const uint64_t nframes)
{
    rows = nrows;
    cols = ncols;
    frames = nframes;
}

template <typename T>
Matrix<T>::Matrix(const uint64_t rows, const uint64_t cols, const uint64_t frames)
{
    Matrix<T>(rows, cols, frames, malloc(rows * cols * frames * sizeof(T)));
}

template <typename T>
Matrix<T>::Matrix(const uint64_t rows, const uint64_t cols, const uint64_t frames, T *data)
{
    sz = Size(rows, cols, frames);
    _data = data;
}

template <typename T>
void Matrix<T>::print()
{
    printf("[");
    for (uint64_t f = 0; f < sz.frames; f++) {
        printf("[");
        for (uint64_t r = 0; r < sz.rows; r++) {
            for (uint64_t c = 0; c < sz.cols; c++) {
                printf("%.3f,", element(r, c, f));
            }
            printf("\n");
        }
        printf("]\n");
    }
    printf("]\n");
}

測試

#include "core.h"

int main(int argc, char *argv[])
{
    int data[] = { 1, 2, 3, 4, 5, 6, 7, 8};
    Matrix<int> mat(2, 2, 2, data);
    mat.print();
    return 0;
}

錯誤

Undefined symbols for architecture x86_64:
  "Matrix<int>::print()", referenced from:
      _main in rand.cpp.o
  "Matrix<int>::Matrix(int, int, int, int*)", referenced from:
      _main in rand.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[2]: *** [examples/rand] Error 1
make[1]: *** [examples/CMakeFiles/rand.dir/all] Error 2
make: *** [all] Error 2

我確定它很小,但我無法弄清楚。 任何幫助將非常感激!

模板函數(包括模板類的成員函數)需要在頭文件中實現,因此它們的定義(不僅是聲明)在所有可能使用它們的翻譯單元中都是可見的。 有關更多信息,請參見此SO問題

將構造函數的定義和print函數移到Matrix類模板的定義下方的頭文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM