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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With