mardi 14 septembre 2021

Undefined reference to a class file [duplicate]

I get this error when I try to compile my code

$ g++ main.cpp -o test
/usr/bin/ld: /tmp/ccPPIE7u.o: in function `main':
main.cpp:(.text+0x37): undefined reference to `Board<11, 11>::Board()'
/usr/bin/ld: main.cpp:(.text+0x8f): undefined reference to `Board<11, 11>::insert(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int, int, int)'
/usr/bin/ld: main.cpp:(.text+0xbc): undefined reference to `Board<11, 11>::show()'
collect2: error: ld returned 1 exit status

This is my code

board.hpp

#include <iostream>

using str = std::string;

template<int rows, int cols>
class Board{
    private:
        str board_string;
        str board_arr[rows][cols];
    public:
        void insert(str elem, int row=0, int col=0, int row_span=1, int col_span=1);
    private:
        void initialise();
    public:
        Board();
        void show();
        
};

board.cpp also here in the constructor I will put some more code, I just compiled to check is everything ok

#include "board.hpp"

using str = std::string;

template<int rows, int cols>
void Board<rows, cols>::insert(str elem, int row, int col, int row_span, int col_span){
    int n_factor=0;
    for(int r =0; r<rows; r++){
        for(int c=0; c<cols; c++){
            if (c==col+n_factor and r==row+n_factor){
                board_arr[c][r] = elem[n_factor];
            }
            if (n_factor < row_span-1){
                n_factor += 1;
            }
        }
    }
}

template<int rows, int cols>
void Board<rows, cols>::initialise(){
    str ret;
    for(int c =0; c<rows; c++){
        for(int r=0; r<cols; r++){
            board_arr[c][r] == " ";
            ret += board_arr[c][r];
        }
    }
    board_string = ret;
}

template<int rows, int cols>
Board<rows, cols>::Board(){
    Board::initialise();
}

template<int rows, int cols>
void Board<rows, cols>::show(){
    std::cout << board_string << "\n";
}

main.cpp

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


int main(int argc, const char** argv){
    Board<11, 11> board;
    board.insert("p", 4, 4);
    board.show();
    return 0;
}

I tried doing g++ main.cpp board.cpp -o test but it still pops the same error

/usr/bin/ld: /tmp/ccPPIE7u.o: in function `main':
main.cpp:(.text+0x37): undefined reference to `Board<11, 11>::Board()'
/usr/bin/ld: main.cpp:(.text+0x8f): undefined reference to `Board<11, 11>::insert(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int, int, int)'
/usr/bin/ld: main.cpp:(.text+0xbc): undefined reference to `Board<11, 11>::show()'
collect2: error: ld returned 1 exit status

Also they are all in the same folder, I don't know why this error comes. How can I fix this? Also is it related to g++ or my code

Aucun commentaire:

Enregistrer un commentaire