How do you define a global function in C++?

Cory Klein picture Cory Klein · Jul 29, 2011 · Viewed 83.7k times · Source

I would like a function that is not a member of a class and is accessible from any class.

I assume I would have to #include the header file where the function is declared, but I don't know where to define such a global function.

Are there good reasons against having such a function in the first place?

Answer

Necrolis picture Necrolis · Jul 29, 2011

you need a body (in a cpp file):

int foo()
{
    return 1;
}

and a definition/prototype in a header file, which will be included before any use of the function:

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    int foo();
#endif

then using it somewhere else:

#include foo.h
void do_some_work()
{
    int bar = foo();
}

or use an inline function (doesn't guarantee it'll be inlined, but useful for small functions, like foo):

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    inline int foo()
    {
        return 1;
    }
#endif

alternatively you can abuse the C-style header based functions (so this goes in a header, the static forces it to exist in a single compilation unit only, you should avoid this however):

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    static int foo()
    {
        return 1;
    }
#endif