Search code examples
c++static-methods

Static function declared but not defined in C++


I'm getting an error from the following code using C++.

Main.cpp

#include "file.h"

int main()
{
   int k = GetInteger();
   return 0;
}

File.h

static int GetInteger();

File.cpp

#include "file.h"

static int GetInteger()
{
   return 1;
}

The error I get:

Error C2129: static function 'int GetInteger(void)' declared but not defined.

I've read the famous article "Organizing Code File in C and C++", but don't understand what is wrong with this code.


Solution

  • In C++, static at global/namespace scope means the function/variable is only used in the translation unit where it is defined, not in other translation units.

    Here you are trying to use a static function from a different translation unit (Main.cpp) than the one in which it is defined (File.cpp).

    Remove the static and it should work fine.