Are inner functions automatically declared in C++?

Viewed 90

Consider a file functions.cpp:

// functions.cpp

void f1(){/* do something */}

void f2()
{
    f1();
}

I wish to use the function f2 in a different cpp file, so I create a header file functions.h:

// functions.h

#ifndef F2
#define F2

void f2();

#endif

Now, the main.cpp file is where I call f2:

// main.cpp

#include "functions.h"

int main()
{
    f2();
    return 0;
}

Compiling this works fine, but I haven't declared f1 in functions.h. So when f2 is called, how does the compiler know about f1?

2 Answers

When main.cpp is translated, an external reference is generated to the function f2. Roughly speaking, this means that the object file generated by the compiler contains instructions to call a function at a certain address, and leaves metadata telling the linker to fill in the actual address of f2. Separately, the compiler translates functions.cpp and internally resolves the reference from f2 to f1 and emits an object file containing the definition of f2. Then the linker, seeing both the object file containing f2 and the object file requiring the address of f2, "links" them together into an executable. Thus, the caller of f2 does not need to be aware of the declarations of any entities used by f2.

void f1(){/* do something */} is both a declaration and a definition of f1 and it is visible to f2. Source files are parsed top-down. So f2 has all it needs and callers of f2 don't need to know about f1.

Related