Learn
Functions: Scope & Flexibility
Multi-File Programs

Programs can grow quickly. With a few functions, you can declare the function above main() and then you can define the function below main() like this:

#include <iostream> // Declaration at the top: void eat(); int main() { eat(); } // Definition at the bottom: void eat() { std::cout << "nom nom nom\n"; }

But this isn’t ideal when your code gets longer; it’s common to use the same function in more than one .cpp file.

To make your code cleaner and more modular, you can move the function definitions over to another specialized .cpp file (e.g., my_functions.cpp), leaving a list of declarations above main().

But files, like functions, have scope. So, how does the main() program know about the function definitions?

Before your program even compiles, it links together any files you list in your compilation statement into a single executable:

g++ main.cpp my_functions.cpp

And voila! Your program knows the function definitions.

Instructions

1.

In main.cpp, we have a program with a few functions. Let’s move them into a different file.

First, add a declaration for each function in main.cpp above the functions above main().

2.

Now, move all of the function definitions over to my_functions.cpp.

3.

Finally, compile and execute your code. Remember to link the two .cpp files when compiling.

Folder Icon

Take this course for free

Already have an account?