Mokus
Mokus

Reputation: 10400

Why does my class not link?

This week I started to upgrade my knowledge from C to C++, I would like to overload some operators

I have a class called Matrix

#include "lcomatrix.h"

inline Matrix::Matrix(unsigned rows, unsigned cols) :
        rows_(rows), cols_(cols)
{
        data_ = new double[rows * cols];
}

inline Matrix::~Matrix() {
    delete[] data_;
}

inline double& Matrix::operator()(unsigned row, unsigned col) {
    return data_[cols_ * row + col];
}

inline double Matrix::operator()(unsigned row, unsigned col) const {
    return data_[cols_ * row + col];
}

The content of lcomatrix.h is

#include <iostream>

class Matrix {
public:
    Matrix(unsigned rows, unsigned cols);
    double& operator()(unsigned row, unsigned col);
    double operator()(unsigned row, unsigned col) const;

    ~Matrix(); // Destructor        
    Matrix& operator=(Matrix const& m); // Assignment operator      

private:
    unsigned rows_, cols_;
    double* data_;
};

Main.cpp

#include "lcomatrix.h"
#include <iostream>


/*-
 * Application entry point.
 */
int main(void) {

    Matrix mx(12,12);

    //std::cout << mx << std::endl;

    return 0;
}

Make file:

CPPFLAGS=-I /path/lcomatrix/
EFLAGS=

all : main.o lcomatrix.o
    g++ $(EFLAGS) -o main.out  main.o lcomatrix.o 

main.o: lcomatrix.o
    g++ $(EFLAGS) $(CPPFLAGS) -c main.cpp

lcomatrix.o: 
    g++ $(EFLAGS) -c /home/robu/UbuntuOne/ChibiOS-RPi/lcomatrix/lcomatrix.cpp

clean:
    rm *.o main.out 

When I try to build I receive the following link error:

make all 
g++  -c /home/robu/UbuntuOne/ChibiOS-RPi/lcomatrix/lcomatrix.cpp
g++  -I /home/robu/UbuntuOne/ChibiOS-RPi/lcomatrix/ -c main.cpp
g++  -o main.out  main.o lcomatrix.o 
main.o: In function `main':
main.cpp:(.text+0x1b): undefined reference to `Matrix::Matrix(unsigned int, unsigned int)'
main.cpp:(.text+0x2c): undefined reference to `Matrix::~Matrix()'
collect2: error: ld returned 1 exit status
make: *** [all] Error 1

I guess this a really stupid error, but as a beginner I couldn't figure out the solution.

Upvotes: 0

Views: 290

Answers (1)

moonshadow
moonshadow

Reputation: 89065

Your method definitions are all inline. In order to inline a function, the compiler needs to see its definition whenever it is compiling the code that uses it.

Either put the function definitions somewhere they can be seen at the point of use - in the header, or in another file #included by Main.cpp - or don't mark them as inline.

Upvotes: 5

Related Questions