2.8 — Programs with multiple code files

Adding files to your project

As programs get larger, it is common to split them into multiple files for organizational or reusability purposes. One advantage of working with an IDE is that they make working with multiple files much easier. You already know how to create and compile single-file projects. Adding new files to existing projects is very easy.

For Visual Studio users

In Visual Studio, right click on the Source Files folder in the Solution Explorer window, and choose Add > New Item….

Make sure you have C++ File (.cpp) selected. Give the new file a name, and it will be added to your project.

Note: If you create a new file from the File menu instead of from your project in the Solution Explorer, the new file won’t be added to your project automatically. You’ll have to add it to the project manually. To do so, right click on Source Files in the Solution Explorer, choose Add > Existing Item, and then select your file.

Now when you compile your program, you should see the compiler list the name of your file as it compiles it.

For Code::Blocks users

In Code::Blocks, go to the File menu and choose New > File….

In the New from template dialog, select C/C++ source and click Go.

You may or may not see a welcome to the C/C++ source file wizard dialog at this point. If you do, click Next.

On the next page of the wizard, select “C++” and click Next.

Now give the new file a name (don’t forget the .cpp extension), and click the Add button to ensure all build targets are selected. Finally, select finish.

Now when you compile your program, you should see the compiler list the name of your file as it compiles it.

For GCC/G++ users

From the command line, you can create the additional file yourself, using your favorite editor, and give it a name. When you compile your program, you’ll need to include all of the relevant code files on the compile line. For example: g++ main.cpp add.cpp -o main, where main.cpp and add.cpp are the names of your code files, and main is the name of the output file.

A multi-file example

In lesson 2.7 -- Forward declarations and definitions, we took a look at a single-file program that wouldn’t compile:

When the compiler reaches the function call to add on line 5 of main, it doesn’t know what add is, because we haven’t defined add until line 9! Our solution to this was to either reorder the functions (placing add first) or using a forward declaration for add.

Now let’s take a look at a similar multi-file program:



Your compiler may decide to compile either add.cpp or main.cpp first. Either way, main.cpp will fail to compile, giving the same compiler error as the previous example:

main.cpp(5) : error C3861: 'add': identifier not found

The reason for is exactly the same as well: when the compiler reaches line 5 of main.cpp, it doesn’t know what identifier add is.

Remember, the compiler compiles each file individually. It does not know about the contents of other code files, or remember anything it has seen from previously compiled code files. So even though the compiler may have seen the definition of function add previously (if it compiled add.cpp first), it doesn’t remember.

This limited visibility and short memory is intentional, so that files may have functions or variables that have the same names without conflicting with each other. We’ll explore an example of such a conflict in the next lesson.

Our options for a solution here are the same as before: place the definition of function add before function main, or satisfy the compiler with a forward declaration. In this case, because function add is in another file, the reordering option isn’t a good one.

The better solution here is to use a forward declaration:

main.cpp (with forward declaration):

add.cpp (stays the same):

Now, when the compiler is compiling main.cpp, it will know what identifier add is and be satisfied. The linker will connect the function call to add in main.cpp to the definition of function add in add.cpp.

Using this method, we can give files access to functions that live in another file.

Try compiling add.cpp and the main.cpp with the forward declaration for yourself. If you get a linker error, make sure you’ve added add.cpp to your project or compilation line properly.

Something went wrong!

There are plenty of things that can go wrong the first time you try to work with multiple files. If you tried the above example and ran into an error, check the following:

1. If you get a compiler error about add not being defined in main, you probably forgot the forward declaration for function add in main.cpp.

2. If you get a linker error about add not being defined, e.g.

unresolved external symbol "int __cdecl add(int,int)" (?add@@YAHHH@Z) referenced in function _main

2a. …the most likely reason is that add.cpp is not added to your project correctly. When you compile, you should see the compiler list both main.cpp and add.cpp. If you only see main.cpp, then add.cpp definitely isn’t getting compiled. If you’re using Visual Studio or Code::Blocks, you should see add.cpp listed in the Solution Explorer/project pane on the left side of the IDE. If you don’t, right click on your project, and add the file, then try compiling again. If you’re compiling on the command line, don’t forget to include both main.cpp and add.cpp in your compile command.

2b. …it’s possible that you added add.cpp to the wrong project.

2c. …it’s possible that the file is set to not compile or link. Check the file properties and ensure the file is configured to be compiled/linked. In Code::Blocks, compile and link are separate checkboxes that should be checked. In Visual Studio, there’s an “exclude from build” option that should be set to “no” or left blank.

3. Do not #include “add.cpp” from main.cpp. This will cause the compiler to insert the contents of add.cpp directly into main.cpp instead of treating them as separate files. While it may compile and run for this simple example, you will encounter problems down the road using this method.


When the compiler compiles a multi-file program, it may compile the files in any order. Additionally, it compiles each file individually, with no knowledge of what is in other files.

We will begin working with multiple files a lot once we get into object-oriented programming, so now’s as good a time as any to make sure you understand how to add and compile multiple file projects.

Reminder: Whenever you create a new code (.cpp) file, you will need to add it to your project so that it gets compiled.

Quiz time

Question #1

Split the following program into two files (main.cpp, and input.cpp). Main.cpp should have the main function, and input.cpp should have the getInteger function.

Show Hint

Show Solution

2.9 -- Naming collisions and an introduction to namespaces
2.7 -- Forward declarations and definitions

167 comments to 2.8 — Programs with multiple code files

  • Jim

    This may not be the proper place to bring this up but I stall have questions on Functions. (Move it if you'd like!)

    I'm using code::blocks 13-12 on Windows 64, and it's geared toward projects not functions. Therefore a function can not be precompiled, debugged or tested before using it in a program without a main function.

    Certainly the pro's don't write small programs and then take them apart to reuse a function like: readUserName or getPassWord for instance.

    If I wanted to make functions to add, subtract multiply or divide two variables. How do the pro's handle the testing, storage and reuse of functions like these without worry?

    • Alex

      Great question, and here is as good a place to ask this question as anywhere. All IDEs are geared towards projects, not functions, because you compile a project (not a function) with the goal of producing a program.

      Typically experienced programmers will create pairs of files (a .cpp and a .h) that contain generic/reusable functions that implement a set of related functionality. For example, a bunch of math functions, or a reuseable list. Once you get into object-oriented programming, this will probably be implemented as a single class.

      Those .cpp and .h files can then be kept in a common location where they can be accessed (or copied into) by multiple projects (with a backup stored in version control).

      It is possible to precompile .cpp files into libraries (either static or dynamic libraries). I cover how to do this in the appendix of the tutorial. This creates a .lib or .dll on windows, or a .a or .so on unix, which replaces the .cpp file (you still need a corresponding .h file).

      Testing functions and classes is a whole subject in and of itself. One common way to test reusable functionality is to provide a unit test or testing application. Essentially this is a small program that exercises each of the functions and validates that they are producing the correct output. The test can be invoked whenever a change is made to ensure the change hasn't broken anything else.

      So, specific to your case, I'd create a math.cpp with add() and subtract(), and a math.h header that contains the prototypes for add() and subtract(). I might also include a test() function to ensure add() and subtract() work with well known inputs (two positive numbers, two negative numbers, a positive and a negative number) and give the expected results. Then I could include these in any project that needs them.

  • Jim

    How to do this in code::blocks (CB) 13-12.

    Make a new project in CB, I called mine MF-Demo, for multi file demo. MF-Demo will include a main.cpp(Hello World).  Click to open main.cpp (Hello world) and cut it's entire content. (the file is now empty) Copy and Paste main.cpp from this lesson. Now you need to add a new->empty file in CB. Copy and paste add.cpp (from this lesson) into this empty file. Make sure this file is named add.cpp in CB.
    CB should show these file in the editor right next to one another, in the management window they will be listed there to. Now open add.cpp and copy the first line only.(int add (int x, int y) Now open the new main file and paste it above the main.cpp. At the end of this line type in a semicolon. Now you can us CB Build and Run and you should see the results on the console screen....

    Note you can do this in any project but if you do it this way you can delete the entire project later. You could have saved these two file into your PC and copied them from there instead of from this lesson.  I recommend that you print this out and follow it carefully.

    I hope this helps other users.

  • Jim

    Using multi files in one project is a bit confusing since it's hard to understand just what you want us to do here. In this lesson you show main.cpp and add.cpp. But neither one of these functions can be compiled without the other (as shown) or you get errors. (Which you pointed out)

    However the code for each function, can be stored in separate files and located anywhere on a PC. So, I would assume these files were not precompiled and both have been given a .cpp suffix. Is that true?

    I would also assume that every Project must have one and only one, unique main.cpp function that you add new files to in the IDE to build a program.

    Is this what you want us to do? Open a new project and add main.cpp and add.cpp to it and then modify main.cpp so add.cpp will work  Please expand on this.

    What, confuses me is you can't give code a .cpp suffix until you compile it with Code::blocks. What am I missing?

    • Alex

      Both main.cpp and add.cpp are not precompiled, and they have a .cpp suffix.

      Every project must have a main() function. It can live in any file. I typically put mine in either main.cpp, or <application_name>.cpp just so I know where to find it.

      Your sequence of steps is correct if you want to duplicate the example yourself.

      I'm not super-familiar with Code::Blocks, but it sounds suspicious that it wouldn't let you put an extension on a file until you compile it. You should be able to put the extension on it when you either create or save the file.

      For what it's worth, C++ doesn't care about extensions. They're more for our use in keeping things organized.

  • Atul

    Why am I getting this error?
    Error    1    error C1083: Cannot open precompiled header file: 'DebugConsoleApplication7.pch': No such file or directory    c:usersatul ramkrishnandocumentsvisual studio 2013projectsconsoleapplication7consoleapplication7source.cpp    1    1    ConsoleApplication7

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">