Static function declared but not defined in C++
Change
static int GetInteger();
to
int GetInteger();
static
in this case gives the method internal linkeage, meaning that you can only use it in the translation unit where you define it.
You define it in File.cpp
and try to use it in main.cpp
, but main doesn't have a definition for it, since you declared it static
.
functions declared as static arelocal to the containing file. Therefore, you have to define the function in the same file as the ones who call it. If you want to make it callable from other file, you must NOT declare it as static.
Because in this case, static
means that the name of the function has
internal linkage; that GetInteger
in one translation unit is unrelated
to GetInteger
in any other translation unit. The keyword static
is
overloaded: in some cases, it affects lifetime, and in others, binding.
It's particularly confusing here, because "static" is also the name of a
lifetime. Functions, and data declared at namespace scope, always
have static lifetime; when static
appears in their declaration, it
causes internal binding, instead of external.
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.