Static function declared but not defined in C++

Sait picture Sait · May 30, 2012 · Viewed 63.3k times · Source

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.

Answer

HighCommander4 picture HighCommander4 · May 30, 2012

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.