I am getting the following error:
x.h:3:13: warning: ‘int X::foo()’ used but never defined
/tmp/ccK9qSnq.o: In function `main': main.cpp:(.text+0x7): undefined reference to `X::foo()'
collect2: error: ld returned 1 exit status
while building the following code:
#include "x.h"
int main()
{
X::foo();
}
namespace X
{
static int foo();
}
#include "x.h"
namespace X
{
int foo()
{
return 1;
}
}
Can anybody explain the reason?
The linkage of a function declared static
is internal, which means that it may only be referred to from the current translation unit. Even if several translation units see the same declaration, a private version of the function is expected for each one.
What happens in your case is that the function foo that is defined in x.cpp is not available to other translation units. When the compiler translates main.cpp, it annotates the symbol as "missing" but does not complain. Later, at the linking stage, the linker cannot find the private function foo that is referred to in the object main. To solve this, you could:
static
specifier from foo
's declaration in x.h, for which there isn't presumably a reason to be there.The right solution is, of course, the first. The others were explained to show why.
For more information, read this page. Also, note the difference between a declaration and a definition, which is outside the scope of this question.