Question:
c++: undefined reference to.....?
Matthew P
2008-04-24 16:21:32 UTC
I have two objects A, and B. In A i have a function:
A::addB(B *b)
{
int bresult = b->getResult();
..............
}

when compiled with g++ i get:
undefined reference to 'B::getResult()'
I didn't forget to include the header file for B
Four answers:
Angus
2008-04-24 20:58:10 UTC
When you get an "undefined reference" error, your problem won't be solved with #includes (assuming you are trying to link to a method defined in a .cpp, and all your #includes reference only .h files). The reason this is happening is that the object file in which B::getResult() is defined is not being found by the linker. So there is probably a file B.o that will have to be referenced in your linking line. Here's an abstraction of the g++ calls:



g++ -c A.cpp B.cpp

g++ -o myprogram A.o B.o
gonsior
2016-10-06 05:24:01 UTC
Undefined Reference To
mapighimagsik_so
2008-04-24 16:45:01 UTC
What does your compile command look like? You might have to make sure to G++ a.cpp b.cpp



Or something like that.



There are other causes: Is getResult() public on B?
2008-04-24 17:25:13 UTC
Include header for class B before using in class A.

Alternatively, this method will work.



// Header file

class B;

class A

{

public:

void addB(B *);

...

};

class B

{

public:

int getResult();

...

}



// Source file

void A::addB(B *b)

{

int bresult = b->getResult();

...

}

That should fix your problem.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...