Small Steps VIII — Build with Several Files

Split a Program into Two Files

Move a function body to another source file.

Try it in one file first

Example · example.cpp
void say_hello()
{
    print("Hello from another file!");
}

void small_main()
{
    say_hello();
}

We will move say_hello to another file. Continue in the Greeting project from the previous lesson.

Create greeting.cpp

Right-click a blank area in the file list and choose New Source File…. Enter greeting.cpp. The new file opens in a tab. Put the following code in it.

greeting.cpp

void say_hello()
{
    print("Hello from another file!");
}

Replace main.cpp with the following. Remove the body of say_hello from this file and add its declaration at the top.

main.cpp

void say_hello();

void small_main()
{
    say_hello();
}

void say_hello();, ending with a semicolon, introduces the function. The version with braces supplies its body. Choose Run Project: the result is unchanged.

Keep only one small_main in the whole project. Do not #include a .cpp file. The IDE compiles each included .cpp separately and links them together.

Exercise — Check it yourself

Change the greeting in the one-file practice below. Then make the same change in your project's greeting.cpp. Close the main.cpp tab and try Run Project again.

Exercise starter · exercise_starter.cpp
void say_hello()
{
    print("Hello from another file!");
}

void small_main()
{
    say_hello();
}

Hint

Use the menus described above. The solution below is for the one-file practice. Apply the same change to the file with that job in your project.

show solution
void say_hello()
{
    print("Hello, friends!");
}

void small_main()
{
    say_hello();
}
← Previous lessonNext lesson →