Static Functions

Hi,

I was reading some tutorial(Here: www.functionx.com/cpp/index.htm)
and then the tutorial mention static function without any explanation.

Static Functions

Like a variable, a function also can be declared and/or defined as static.


That's all what it says. then it gives this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifdef __BORLANDC__
  #pragma argsused
#endif

#include <iostream>

// #include "Exercise.h"
using namespace std;

static int GetNumberOfPages()
{
  int pages = 842;

  return pages;
}

int main( int argc, char * argv[] )
{
    cout << "This book contains " << GetNumberOfPages() << " pages";

    return 0;
}


I looked it up in Google and here but nothing.

Can anyone please explains to me the static function?
A static function is only known in the file it was declared. It's used a lot in C because there's no namespaces and no classes.
Last edited on

filipe (835):
A static function is only known in the file it was declared. It's used a lot in C because there's no namespaces and no classes.


What do you mean in the file it was declared.is that mean if i create a header file and declare a static function in it, i wouldn't be able to use it in the source file or what?

Can you explain it more simpler and with more details?
If you insert a definition along with the declaration into a header file, it will define a separate function inside all the translation units that use it (translation unit = .cpp + all its #includes).

Static functions are typically meant to be local to a .cpp file.
A static global function won't be visible when linking with other source files
This feature is deprecated in C++ and unnamed namespaces should be used instead:
1
2
3
4
namespace
{
    int GetNumberOfPages() { /*...*/ } // same effect, the C++ way
}
Thanks guys

I get it now.
Topic archived. No new replies allowed.