Guilherme Salome
Guilherme Salome

Reputation: 2039

Compiling .h with .cpp using g++ on the same directory, error

I am learning C++ and I have a Class declaration in a .h file, and the definitions on a .cpp file. The .h file is as follows:

// matrix.h

class Matrix {
 private:
  int r; // number of rows
  int c; // number of columns
  double* d;
 public:
  Matrix(int nrows, int ncols, double ini = 0.0); // declaration of the constructor
  ~Matrix(); // declaration of the destructor
  inline double operator()(int i, int j) const;
  inline double& operator()(int i, int j);
};

And the .cpp is:

// matrix.cpp

#include "matrix.h"

Matrix::Matrix(int nrows, int ncols, double ini) {
  r = nrows;
  c = ncols;
  d = new double[nrows*ncols];
  for (int i = 0; i < nrows*ncols; i++) d[i] = ini;
}

Matrix::~Matrix() {
  delete[] d;
}

inline double Matrix::operator()(int i, int j) const {
  return d[i*c+j];
}

inline double& Matrix::operator()(int i, int j) {
  return d[i*c+j];
}

And the test file is:

// test.cpp
#include <iostream>
#include "matrix.h"

using namespace std;

int main(int argc, char *argv[]) {
  Matrix neo(2,2,1.0);
  cout << (neo(0,0) = 2.34) << endl;
  return EXIT_SUCCESS;
}

Problem: when I compile the test.cpp file using g++ test.cpp, or using g++ test.cpp matrix.cpp, I get the errors: warning: inline function 'Matrix::operator()' is not defined and ld: symbol(s) not found for architecture x86_64.

Question: What is failing? How can I understand what is happening? Thanks for helping!

Upvotes: 0

Views: 88

Answers (1)

M.M
M.M

Reputation: 141554

The body of an inline function should be visible at all callsites of the function.

In your setup you need to move those two inline definitions from matrix.cpp to matrix.h ; or make them non-inline.

Upvotes: 4

Related Questions