C ++ problems with overloading operator + (undefined reference to 'operator + (...)

0

I'm having trouble overloading the + operator in C ++. Anyone have any idea what's wrong?

To perform the unit tests I'm using googletest in Ubuntu. (I wanted to do this to make the code cleaner)

Code:

---- vector.cpp -----

vector<double> operator+(const vector<double>& r1, const vector<double>& r2)
{
  double size;
  size = r1.size();

  if(r1.size() != r2.size()) {
    cerr << "Vector Subtraction Error: Vectors with different dimensions!" << endl;
    exit(1);
  }

  vector<double> r3 (size,0);

  for(int i = 0; i < int(r3.size()); i++)
    r3[i] = r1[i] + r2[i];

  return r3;
}

--- vectorTest.cpp ---

#include <gtest/gtest.h>
#include <vector>
#include "../src/vector.h"

using namespace std;

TEST (SumVectorTest, vector)
{
  vector<double> r1(2);
  vector<double> r2(2);
  vector<double> r3(2);

  r1[0] = 2; r2[0] = 3;
  r1[1] = 3; r2[1] = 17;
  r3 = r1 + r2;

  EXPECT_EQ(r3[0], 5);
  EXPECT_EQ(r3[1], 20);
}

int main(int argc, char * argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

--- terminal ---

$ g++ vectorTest.cpp -lgtest
/tmp/ccNRp61Z.o: In function 'SumVectorTest_vector_Test::TestBody()':
vectorTest.cpp:(.text+0x16d): undefined reference to 'operator+(std::vector<double, std::allocator<double> > const&, std::vector<double, std::allocator<double> > const&)'
collect2: error: ld returned 1 exit status

PS: I was using the same code on a Mac OS X and it did not return me an error.

    
asked by anonymous 22.02.2016 / 15:20

1 answer

1

You have two code files that need to be compiler to generate an executable, but it is only compiling one of them (vectorTest.cpp). A very quick solution would be to include the two command line files, for example:

g++ vectorTest.cpp vector.cpp -lgtest

A long-term solution is to specify a build script (to be used in a make, or cmake, for example)

    
22.02.2016 / 21:40