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?
You have to define the static function either in the header (in this case removing its definition in X.cpp) or additionally in main.cpp. Otherwise main.cpp will not see its definition. In X.cpp there is defined another static function foo with the same name. There is no external linkage for static functions. They have internal linkage and shall be defined in compilation units where they are used.
So X.cpp has its own static function foo which it defined. But main.cpp did not define its own static function with name foo. it only declared it due to inclusion of the header.