Undefined reference to Foo::bar()

From Cppsyntax

Jump to: navigation, search

You can get the error

 undefined reference to `Foo::bar()'

if your makefile isn't correct.

For example, if foo.cc has the definition of Foo in it, and main.cc has a call to aFoo.bar() in it:

WRONG

Makefile:

 main.exe:	main.o 
   g++ -o main.exe main.o $(LIBS)

RIGHT

Makefile:

 main.exe:	main.o foo.o
   g++ -o main.exe main.o foo.o $(LIBS)




You can also get that error if you're using some function that was declared in the header file (.h) as a not inline function but not implemented in the source code (.cc).

Note that the tricky thing is class Foo itself will compile just fine, only when calling the member Foo::bar(), e.g. in Main.cc, the linker will throw the error.

WRONG

Header file "foo.h":

class Foo 
{
public:
   bool foo() { return true; }   //this works, its inline
   bool bar();                   //no inline function, function body still has to be implemented!
}

Source code file "foo.cc" does not contain implementation of Foo::bar().

RIGHT

Header file "foo.h" as above.

Source code file "foo.cc":

bool Foo::bar()
     { return false; }
Personal tools