Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 631
Sait Avatar asked May 30 '12 08:05

Sait


Video Answer


2 Answers

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.

like image 140
HighCommander4 Avatar answered Sep 17 '22 11:09

HighCommander4


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.

like image 41
Luchian Grigore Avatar answered Sep 21 '22 11:09

Luchian Grigore