undefined reference

Hello,

I've been reading Professional C++ by Marc Gregoire and I'm having problems with some of his code.

Here is the code of three files I have taken from the book:

Here is namespace.h

namespace mycode {
void foo();
}

Here is namespace.cpp

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

namespace mycode {
void foo() {
std::cout << "Foo called." << std::endl;
}
}

Here is test.cpp

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

using namespace mycode;

int main()
{
foo();
return 0;
}

When I compile this code I get this error:

undefined reference to `mycode::foo()'

What's causing this ?

TIA

Weasel





"Undefined reference" is a linker error that means it cannot find the definition (implementation) of the function that it is complaining about.

Did you compile and link both namespace.cpp and test.cpp?

If you are using an IDE make sure you have added both .cpp files to the same "project".
Last edited on
Keep in mind that the header file (.h) only contains the declaration of the function mycode::foo(), but the actual implementation of that function is in a separate source file (.cpp). Therefore, #include 'ing the header file only tells the compiler that the function exists, somewhere, but you still have to compile and link the actual implementation too! It is done like this, so that the declaration can be #include 'd at many different places (source codes files) of your project, but the implementation still only needs to exist at one place.

With GCC and similar compilers, you do something like:
1
2
3
g++ -c -o test.o test.cpp
g++ -c -o namespace.o namespace.cpp
g++ -o test.exe test.o namespace.o

(first two lines compile the source code files, last line links the resulting object files together)
Last edited on
Topic archived. No new replies allowed.