DaPhil
DaPhil

Reputation: 1599

Passing a VectorXi from eigen library to class method

The following main file should pass a VectorXi to my class called Test which then has a method that does something with it (for demonstration it just prints the sum of all elements):

#include <iostream>
#include <eigen3/Eigen/Dense>
#include "test.h"

using namespace std;
using namespace Eigen;

int main(int argc, const char * argv[]) {

    VectorXi m(3);
    m[0] = 1;
    m[1] = 2;
    m[2] = 6;

    Test test;
    test.mySum(m);

    return 0;
}

The test.h

#ifndef __CPP_Playground__test__
#define __CPP_Playground__test__

#include <iostream>
#include <eigen3/Eigen/Dense>

using namespace std;
using namespace Eigen;

class Test {
public:
    void mySum(VectorXi vec); // Does not work. 
//    void mySum(VectorXi vec){cout << vec.sum() << endl;}; // Works.
};

#endif /* defined(__CPP_Playground__test__) */

and the test.cpp

#include "test.h"

void mySum(VectorXi vec){
    cout << vec.sum() << endl;
};

When compiling with Xcode 6.1.1 on OS X 10.10.2 I get the error message:

Undefined symbols for architecture x86_64:
  "Test::mySum(Eigen::Matrix<int, -1, 1, 0, -1, 1>)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1

I tried to use libstdc++ instead of libc++ under the project settings but it didn't work. I installed the eigen library using Homebrew via brew install eigen. Why is it working with the method directly defined in test.h (see commented line) but not when it is defined in the test.cpp?

Upvotes: 0

Views: 281

Answers (1)

ggael
ggael

Reputation: 29265

This has nothing to do with Eigen, you simply omitted the class prefix Test:: in the cpp file:

void Test::mySum(VectorXi vec){
    cout << vec.sum() << endl;
}

Moreover, the trailing ; was not needed in proper C++, and you should rather pass the vec object by reference declaring the argument as VectorXi &vec or even better use a Eigen::Ref<VectorXi> vec to allow compatible objects to be passed by reference.

Upvotes: 1

Related Questions