0

I'm having one of those "undefined reference to " errors when compiling a c++ program. I know this is common pitfall, but so far was unable to figure out what I'm doing wrong.

Here's the relevant code. Ex1Two_Sum.h:

#ifndef EX1TWO_SUM_H
#define EX1TWO_SUM_H

#include <vector>
using namespace std;

namespace ddc {
class Ex1Two_Sum
{
   public:
     void f();
   protected:
   private:
};
}

#endif 

Ex1Two_Sum.cpp:

#include <vector>
#include <cstddef> 
#include <iostream>

using namespace std;

namespace ddc {
class Ex1Two_Sum {
public:

  void f(){
    cout << "works" << endl;
  }
};
}

And finally, main.cpp:

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

using namespace std;
using namespace ddc;

int main()
{
  Ex1Two_Sum ex1;
  ex1.f();
  return 0;
}

I compile as follows:

g++ -std=c++11 -c Ex1Two_Sum.cpp 
g++ -std=c++11 -c main.cpp 
g++ Ex1Two_Sum.o main.o 

yielding the following message:

main.o: In function `main':
main.cpp:(.text+0x2c): undefined reference to `ddc::Ex1Two_Sum::f()'
collect2: error: ld returned 1 exit status
nmpg
  • 561
  • 2
  • 10
  • 24

2 Answers2

4

Your source file redefines the whole class, with an inline function definition, when it just needs to provide a non-inline function definition.

#include "Ex1Two_Sum.h"

void ddc::Ex1Two_Sum::f() {
    std::cout << "should work\n";
}

Also, please don't put using namespace std; in a header. Not everyone wants the global namespace polluted in potentially surprising ways.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Yeah. works now -- needed to include iostream to compile. On a related note: would you say this is the usual way to define/use classes in c++? I mean, to have class specification in a .h file, and then a separate file simply implementing the functions? – nmpg Apr 06 '15 at 13:56
  • @nmpg: Yes, that's the usual way to do it. The alternative is to define it all in a header, which is sometimes appropriate (and usually required when defining templates) but can lead to excessive dependencies. – Mike Seymour Apr 06 '15 at 16:02
0

First, which line of the command throws that error?

Second, I think you forgot to include the Ex1Two_Sum.h in the Ex1Two_Sum.cpp

Third you need to change class ....... in Ex1Two_Sum.cpp to:

void Ex1Two_Sum::f(){...}
ch271828n
  • 15,854
  • 5
  • 53
  • 88