C++ problems with overloading Operator+ (Undefined Reference to 'Operator+(...))

Asked

Viewed 81 times

0

I’m having trouble making the operator + overloading in C++. Does anyone have any idea what’s wrong?

To perform Unit tests I am using googletest on Ubuntu. (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 error.

1 answer

1


You have two code files that need to be compiler to generate an executable, but are only compiling one of them (vectorTest.cpp). A very quick solution would be to include the two files in the command line, 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)

  • It worked :) thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.