0

Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?

I recently started working on an interpreter in C++, but I got annoyed that vectors or arrays could not be passed to external class methods no matter what I tried and so I deleted everything I had worked on. As it turns out, I can't pass even an int to another class. I decided to give C++ another chance before resorting to C or Java, but the compiler still doesn't work as I would expect. Maybe I'm forgetting something simple about C++, as I haven't used it in a while, but this seems simple enough. My problem is: I can't pass arguments to methods in other classes when they're not defined in the same file. Here's what I'm trying to do:

Main: main.cpp

#include "myclass.h"

int main() {
    MyClass test;
    int n = test.add(25, 30);
    return n;
}

Header: myclass.h

class MyClass {
public:
    int add(int a, int b);
};

Class implementation: myclass.cpp

#include "myclass.h"

int MyClass::add(int a, int b) {
    return a + b;
}

Compiling this with g++ main.cpp yields

/tmp/ccAZr6EY.o: In function main': main.cpp:(.text+0x1a): undefined reference toMyClass::add(int, int)' collect2: error: ld returned 1 exit status

What the heck am I doing wrong? Also, the compiler yells at me for the same thing even if my functions aren't parameterized, so it must be a problem with the header.

Any help is much appreciated - thanks!

Community
  • 1
  • 1
ICoffeeConsumer
  • 882
  • 1
  • 8
  • 22

1 Answers1

2

You need to compile both files

g++ main.cpp myclass.cpp

If you only compile main.cpp, the compiler finds the declaration of MyClass::add in your header but the linker later fails to find an implementation of MyClass::add to jump to.

simonc
  • 41,632
  • 12
  • 85
  • 103