Static functions outside classes

At namespace scope, static gives a name internal linkage, meaning that it is only accessible within the translation unit that contains the definition. Without static, it has external linkage, and is accessible in any translation unit.

So you'd use static (or, alternatively, an unnamed namespace) when writing a function that's only intended for use within this unit; the internal linkage means that other units can define different functions with the same name without causing naming conflicts.

Non-static functions (and global names in general) are better declared in a header, to make sure that every translation unit that uses them gets the same declaration.


The static keyword on global functions or variables limits the visibility and linkage scope of the function or variable to the current translation unit.

That means that for a function, it can only be called from the current source file, and not from other source files.


A static function remains visible only in file scope. This is a C feature.
The recommended way to do it in C++ is using an anonymous namespace, as in:

namespace // no name, i.e. anonymous
{
   void someRandomFunction(); 
}

int main()
{
    someRandomFunction(); // visible only within this file.
    return 0;
}

Note that the function body also has to be declared somewhere within the same file since the linker will not try to find it in other (external) translation units.
So void someRandomFunction(); is really a forward declaration for a function that is defined elsewhere in the same file (i.e. in the same translation unit).

If the function is actually called, you will get a linking error unless the function body is defined in the same file.

(The more pedantic technical term is actually not file but translation-unit since the body might be in an #includeed header do not in the actual file per-se. )