2.7 — 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.6 -- 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:



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)" ([email protected]@[email protected]) 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.


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.8 -- Naming collisions and an introduction to namespaces
2.6 -- Forward declarations and definitions

460 comments to 2.7 — Programs with multiple code files

  • Guocheng Qian

    for g++ useer: g++ l2.7.cpp add.cpp -o l2.7 -std=c++17

    • nascardriver

      You don't have any extra warnings using this. Here's a list of warnings you can use with gcc

      Look into CMake or Meson to make working with large projects easier.

  • Hey guys! I added a file in my project called add.cpp and my compiler (code) gave me a lot of errors while trying to include my file. I'll throw the code in there in hopes of a good samaritan hopping in lol.


    #include <iostream>
    #include "add.cpp"

    int userInput(){
        std::cout<<"enter an integer \n";
        int choice{};
        std::cin>&gt; choice;
        return choice;

    int doubleNumber(int x){
        int x2{x*2};
        return x2;

    int add(int x, int y); // needed so main.cpp knows that add() is a function declared elsewhere

    int main(){
        int choice{userInput()};
        std::cout<<"double "<<choice<<" is="" "<<doublenumber(choice)<<'\n';="" int="" choice2{userinput()};="" std::cout<<choice<<"="" and="" "<<choice2<<"="" "<<add(choice,choice2)<<'\n';="" return="" 0;="" }="" [="" code]="" add.cpp:="" [code]="" #include="" "main.cpp"="" add(int="" x,="" y){="" x="" +="" y;="" <="" div=""></choice<<"></iostream>

    • Guy




      The main problem is you used #include, when you shouldn't. #include just copies the code from a file to the other. So it copies add.cpp to main.cpp, which makes the compiler to define the "add" function twice, which causes the error. And also it copies the main.cpp to the add.cpp, which leads to more errors. You should just let the IDE to do the job here, it's the point here. The IDE would tell the compiler that it's compiling the two files into one exe. You should not add it manually.

      #include thing is learnt very soon through this tutorial by the way. And probably you already see it. :P

  • Naveen

    I was searching to create a project on visual studio code to use this multi file application. But unfortunately I couldn't find any options that you have shown in the above images

    So please help me out......

    • abrattic

      The software they are using above is Visual Studio (IDE) not Visual Studio Code. Find a tutorial online to create a tasks.json file in VSCode and how to compile using it.

  • Haldhar Patel

    Consider the following code:



    It is said that compiler will compile each file independently without the knowledge of other files and it is done intentionally to avoid naming conflict from other files, still why I am getting error on compiling the above program as

    In function `add(int, int)':
    add.cpp:(.text+0x0): multiple definition of `add(int, int)'
    /tmp/ccf5KNnP.o:main.cpp:(.text+0x0): first defined here
    collect2: error: ld returned 1 exit status

    --Why it is checking the other file for add function if it is already defined on the main function..?

    • Alex

      The compilers will compile add.cpp and main.cpp separately, and they will compile fine. However, when the linker combines these files together, the linker will determine that you've provided two separate definitions for function add() and this violates the one definition rule.

      We cover this topic in more depth when we discuss internal linkage ( and external linkage (

      The easiest way to fix this would be to convert the full definition of add() in main.cpp to a forward declaration. In that case, the add() in add.cpp will be the only definition and the linker will connect calls to add() from main.cpp to the add() function definition in add.cpp.

  • Prajwal

    i use VS code, i downloaded an extension to combine files, so after selecting the two separate files using ctrl + left click , then right click and there is an option saying combine which I press but I am still getting an error . I use code runner extension as well, is that causing a problem ??

    the error i was getting :::  

    Windows PowerShell
    Copyright (C) Microsoft Corporation. All rights reserved.

    Try the new cross-platform PowerShell

    PS Z:\My C PROGRAMS\C++> cd "z:\My C PROGRAMS\C++\" ; if ($?) { g++ main.cpp -o main } ; if ($?) { .\main }
    C:\Users\PRAJWA~1\AppData\Local\Temp\ccuZ5kAM.o:main.cpp:(.text+0x3d): undefined reference to `add(int, int)'
    collect2.exe: error: ld returned 1 exit status
    PS Z:\My C PROGRAMS\C++>

  • Lorton

    I'm loving these tutorials so far!

    Though from time to time during the last couple of days, I couldn't access the website, and it only displayed a white screen with "Origin Error" on it, seems to be fixed now though.

    Just wanted to know if it was a problem on my end, and if so, suggestions on fixing it in case it pops up again?
    Or maybe the site was just under maintenance.

    Thanks again to you guys for making this awesome content!

  • Mark

    When using Visual Studio on Windows, I only have the options "Class..." and "Resource..." when I right-click on "HelloWorld" and move with the cursor over "add".

    Also, the line starting with "Solution" is not in the solution explorer.

    What is going on?

  • PussyDestroyer69

    is ```int x{}``` the variable x value-initialized to 0 or is it equal to an uninitialized variable ```int x;```?

  • Niels Roetert

    I can compile the two files on the Linux command line fine with g++ and the program works, in VSCode (version 1.51.1) on Linux it doesn't seem to work, probably because there is no concept of an project? I did install the Create C/C++ Project extension, but that didn't help.
    The error ends in "/C++/multipleFiles/main.cpp:7: undefined reference to `add(int, int)"

    Love the site by the way, donated $10 yesterday because I like it so much, looking forward to the other chapters.

    • nascardriver

      The error indicates that you didn't compile "add.cpp", only "main.cpp". I don't know the extension you're using and I can't recommend using extensions to compile code. If the author of that extension removes it from the store or you switch editors, you won't be able to compile your code anymore. Look into CMake or Meson, or write a script that compiles your code instead. If you need help with any of those, feel free to ask.

    • Hey there, Good work on donation. I started learning today. Also using VSCode. The Problem with code editor is more manual configurations. So, you need to know more tweaks in VSCode. Visit and do more tweaks to learn more :

      Just tweak the task.json with below code. Remember to remove the two file configuration after use.

      it's like : g++ -std=c++17 -g Excercise_001.cpp TwoTimerGuy.cpp -o GoodBoy.exe

      feel free to connect : [email protected]

  • N9

    Thank you so much for making this entire guide. I hope you'll continue to maintain it and this site because it is beyond useful.

  • 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

    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:


    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>



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

    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.

    • 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()
        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]