Search

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.

Best practice

When you add new code files to your project, give them a .cpp extension.

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 All 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 use a forward declaration for add.

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

add.cpp:

main.cpp:

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 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.

Summary

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
Index
2.7 -- Forward declarations and definitions

437 comments to 2.8 — Programs with multiple code files

  • sam p

    Before discovering this site, I tried a number of highly rated textbooks and a couple of video courses to try getting my head around C++. This site beats them all, and it's not even close. Many Thanks for putting all of this together. I'm looking forward to completing all the lessons.

    Possible typo:
    "The reason for is exactly the same as well:"
    should be:
    "The reason for this is exactly the same as well:"
    ?

    Thanks again.

  • Spero

    I just want to say that the construction of this tutorial is beautiful. Even though I just learned about scope a few lessons ago and I felt that I understood it I didn't TRULY get it until the quiz question in this lesson. Initially I couldn't understand how 'x' could be used in both functions or how 'y' could get the result of 'getInteger', or really how 'y' could get a result different from 'x'. I compiled and ran it anyway after writing it and to my surprise it asked for my input twice, well of course it did the function was called twice! It seems so obvious now but if this tutorial hadn't been set up as it was I wouldn't have had the background information to make it so obvious once I saw it. The function is called twice so it gets two inputs stored as 'x' and 'y' in the main function, the 'x' in getInteger is only stored there. So in this one lesson you've cemented in my head forward declarations, scopes, calls, different ways to achieve results and have really given me a much more solid base to stand on. Again, it's just beautiful and I so look forward to the rest of the tutorial, thank you!

  • Cloud_Chaser

    Hello,
    I'm totally new to Code::Blocks
    I'm trying to compile 2 files together but I can't add input.cpp to main.cpp
    I am not able to check the add file checkbox...
    What should I do?

    Using Code::Blocks 20.03 on Microsoft Windows 10.

  • Uyph

    Hello, I'm learning two work with multiple files but is met with this error:
    main.cpp

    checkASCII.cpp

    when i try to compile main.cpp, the error is "undefined reference to checkASCII(char). What am i doing wrong here?

    • nascardriver

      You're not compiling "checkASCII.cpp" alongside "main.cpp". Look up how to add a source file in your IDE

      • Uyph

        i think i did compile both of them, the checkASCII file is inside the same source folder as main.cpp. I checked the suggested errors and none of them applied to my case : ( Is it because i didnt include a header file in my main.cpp? i just assumed from this chapter that only an additional .cpp file is needed

  • Ethan C Rush

    #include <iostream>

    add.cpp

    main.cpp

    this is what im assuming its supposed to look like and it wont succeed i get this.

    1>------ Build started: Project: hello world, Configuration: Debug Win32 ------
    1>hello world.cpp
    1>C:\Users\Gaming\source\repos\hello world\hello world\hello world.cpp(3,4): error C3927: '->': trailing return type is not allowed after a non-function declarator
    1>C:\Users\Gaming\source\repos\hello world\hello world\hello world.cpp(3,4): error C3484: syntax error: expected '->' before the return type
    1>C:\Users\Gaming\source\repos\hello world\hello world\hello world.cpp(5,1): error C3613: missing return type after '->' ('int' assumed)
    1>C:\Users\Gaming\source\repos\hello world\hello world\hello world.cpp(5,1): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
    1>C:\Users\Gaming\source\repos\hello world\hello world\hello world.cpp(3,5): error C2146: syntax error: missing ';' before identifier 'cpp'
    1>main.cpp
    1>Generating Code...
    1>Done building project "hello world.vcxproj" -- FAILED.
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    added #iostream to add.cpp and now i dont see main.cpp in the compiler

    removed it and now neither add or main cpp show up in comp.

  • Jim177

    Alex,
    Your method show here does not seem to work with C::B 20.3 W-10 for some reason.  I've tried many ways to fix this but the method you show doesn't work on multi files.  If I save the main.cpp then I try to add file (add.cpp) it has to be given a the full path name and saved to work. (not just add.cpp as you've shown.) If I use C:/CBProjects/main.cpp it doesn't work at all.

    Is it possible that you may have left out a step in your lesson?  What should we us as a full path to save here?  I'm using the path show above.
    Thanks

    • nascardriver

      You need to do this in an already existing project.

    • Jim177

      Wow I finally got the multi file Process to worked.
      I had to make an entirely new project I called testing to do this.

      Then I copied main.cpp from lesson 2.8 with the "forward declaration" with add function. Once I did this I made the new>file>add.cpp. I had to use the full for the testing project for the name path, (you showed add.cpp in the lesson.) I used (C:\CBProjects\testing) there. It put main.cpp and add.cpp into the management window on the left side. I copied app.cpp from lesson 2.8 again, into the editors add function. I also checked the properties of both files to make sure the would compile and link. The first time I ran build/run the file worked, but I got a red process terminated with status 1073741510 in the build log.
      I ran the process again and it ran great and the red build log signal went away.

      I hope this post will help other C::B Users. Just remember to make a new project and substitute CBProjects above in the full path with whatever you used there.

  • Peter

    It seems that, at least in my case that in add.cpp i still have to add #include <iostream>, is that normal?

  • sv

    can someone tell me how to work with separate .cpp files in atom IDE?

    • James Clarks

      Atom, is a simple Text editor, built on chromium, why dont you just use Code::blocks.

      Atom is owned be github, and github is owned by Microsoft, and Microsoft already have a alternative, to Atom, and they are putting a lot of work of, it, If you Just dont want to use code::blocks you should consider using `vs code` rather then Atom.

  • rupp_bin

    Can someone please tell me why am i getting this error
    Error :-
    undefined reference to `add(int, int)'
    ld returned 1 exit status
    my main.cpp
    #include <iostream>
    int add(int x,int y);

    int main()
    {
        std::cout<<add(3,5);
        return 0;
    }
    my add.cpp
    int add(int x,int y){
    return x+y;
    }

  • keshav

    In the quiz time Q#1, you haven't defined y and nor did it holds a value neither a value entered by the user.
    you have only given a value (entered by the user)for x not for y. Should'nt it show undefined behaviour?

    • nascardriver

      `getInteger`'s `x` has nothing to do with `main`'s `x`. A function can't see variables declared in other functions.
      `main`'s `x` is initialized with the return value of `getInteger`, and so is `y`. See lesson 2.2 for an explanation of return values.

  • In Code Lite I didn't have to #include<iostream> in the second file.   In Visual Studio, I did have to do this.  Should I worry about that?  Or not?

    • nascardriver

      Yes, worry about it. Always include everything you use. If your second file uses something from <iostream>, then include <iostream> in the second file. As you already found out, if you don't do this, your code won't work with other compilers.

  • nameless

    "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."

    About that, can we somehow avoid declaring function prototype in every file where we need to use it? Is there a way to, like in some other programming laguages, to somehow import whole file in separate kind of namespace and use functions defined in it?

    • nascardriver

      This is done via header files, which we cover later in this chapter.

      C++20 replaced header files with modules, but no compiler supports modules yet. Headers will continue to work.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]