C++ static local function vs global function

Arun picture Arun · Feb 7, 2013 · Viewed 31k times · Source

What is the utility of having static functions in a file ?

How are they different from having global functions in a file ?

static int Square(int i)
{
   return i * i;
} 

vs

int Square(int i)
{
   return i * i;
}

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Feb 7, 2013

What is the utility of having static functions in a file?

You can use these functions to provide shared implementation logic to other functions within the same file. Various helper functions specific to a file are good candidates to be declared file-static.

How are they different from having global functions in a file?

They are invisible to the linker, allowing other compilation units to define functions with the same signature. Using namespaces alleviates this problem to a large degree, but file-static functions predate namespaces, because they are a feature inherited from the C programming language.