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)" (?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.


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

445 comments to 2.7 — Programs with multiple code files

  • Leon

    How does the Linker know, which definition from which file to choose? Let's say, I extend your example with the add and main function in two different files with a third file add2.cpp in which I also define the add function.
    This should compile, since every definition occurs once per file, right? Then which definition will actually be used? Or will I get a Linker Error?

    Best regards, awesome tutorial!


  • Simone

    Hi Alex, I have some problems using forward declarations together with header files. Could you please help me understand the issue?

    I have a project ("Project1") that includes three files:
    - a header file "declarations.h":

    - the file "silly_function.cpp":

    - and "project.cpp":

    using Dev C++, I have the following error messages:

    Isn't this a good way to make forward declarations?

    thank you for your help,

  • Kol

    Hi, Im using Atom and I was able to create the main.cpp and input.cpp with the exact same code however, when I compile and run it, it wont
    work without the #include "input.cpp" in main.cpp (Is this the right way of doing it using Atom because I know you said its discouraged?)

    Here is the code for main.cpp:

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

    int getInteger();

    int main()
       int x{getInteger()}, y{getInteger()};

       std::cout << x << " + " << y << " is " << x + y << "\n";

      return 0;

    Here is the code for input.cpp:

    #include <iostream>

    int getInteger()
      int x;
      std::cout << "Enter an integer: ";
      std::cin >> x;
      return x;

    • You need to compile both files, not just main.cpp.

    • jaffaman

      In your C++ Compile Options in Atom, add your other files to the the parameters..

      EG: function.cpp -pedantic-errors -Wall -Weffc++ -Wextra -Wsign-conversion

      As a more usable workaround, that will work for all projects, try this:
      Ensure your main function has an extension of cpp... and all additional files get cxx.

      Then, in the parameters, use:
      *.cxx -pedantic-errors -Wall -Weffc++ -Wextra -Wsign-conversion

      Otherwise, it will include the main.cpp multiple times during compile.

      Should get you through the tutorial ok... I hope to find a better solution/or modify the existing plug-in.. but that is beyoud my capabilities right now..

      Think ideally, there would just be a check box option to include other files in folder.

  • nicolas

    how can I do this in atom ??????
    please help

  • MrStark

    Alex,do we need to add " #include <iostream"> and "using namespace std;" in every file we write in project. I am using code block on windows machine with standards of 2014. When I only write above two instructions in only main file, i get error. I had to write these on all files.

  • yadnesh

    I have a doubt in the part 'Adding files to your project from the command line' i tried “g++ main.cpp add.cpp -o main” but it says 'g++ is not recognized as an internal or external command, operable program or batch file'. Please help how to deal with it.

    I am using visual studio on windows. Do i need to add g++ to path or does the installer does it for me. Also if I need to add it to path how do I do it?

  • sri

    when calling add function in add.cpp in main.cpp, do we not need to #include "add.cpp" in main.cpp?

    • nascardriver

      Hi sri!

      No, don't include source files!
      The compiler compiles all source files automatically and, because of the declaration of @add in @main.cpp, the compiler knows that the function is defined elsewhere.

  • Hebi

    I don't know what happened to my visual studio but I set up the files right like in the tutorial. Included all the head files that I needed to, did the forward declaration in my main file. I have even made one
    add.cpp file in each directory that I can find using the solution manager. But the error kept showing up saying that add() is undefined. And I checked out multiple websites they kept saying there is supposedly a 'Source Files' but there isn't. There are only debug and release files. With the Release files containing all the .cpp files. The program worked when I do #include add.cpp but did not when I just compile everything somehow. That means the add.cpp is in the needed directory that my program can find but it just do not want to compile with it, I dont see any 'include to solution' thinggy either.
    The even weirder thing is, when I make another project, it now confirms to the source file,head file structure and I can do the multiple file again. I think it was because of me not accessing the sln file when I am using visual studio. And apparently the file directory does not work if I click create new file.

    • Alex

      If you only see "Debug and Release" folders, then you probably have the "Show All Files" icon checked (it's the third icon from the right in the Solution Explorer pane). Try unchecking that and making sure your add.cpp appears under Source Files.

  • Adam

    it says unknown type name g. I have been stuck on this problem for days can you help?

    #include <iostream>
    g++ ./main.cpp ./add.cpp    
        int add(int x, int y);
        int main()
            std::cout << "The sum of 3 and 4 is: " << add(3,4) << std::endl;
            return 0;

    • nascardriver

      Hi Adam!

      That's not part of the program, that's the command used to compile your source code.



      In your terminal, in the same directory as your files:

      • Adam

        So how do i get the two files to combine in a project. both the files are in the same folder. Im using a ide called Coderunner on my mackbook

    • nascardriver

      If you're using an IDE you don't need to manually run g++ or any other compiler.
      I never used coderunner, I guess you can just press run or "build" somewhere. If that doesn't help you'll need to read a guide or watch a setup video.

  • Sasanka

    How to separate the program to different files in Dev c++. I am using Dev c++. Should I use visual studio instead?

  • Andrew

    I have a question. When putting code in an IO file, should it only contain one function or can it contain many?

    • nascardriver

      Hi Andrew!

      You can have as many functions as you want in one file.
      I suggest you to only have similar functions in the same file to avoid cluttered code.

  • Rajsekar

    Dear Alex,
              Your c++ tutorial is very well explained. Its fanstastic. Thank you for creating this website. u r AWESOME:)

  • Osama

    Hi Alex
    How do I compile/link multiple files using command under Linux?

  • Priyadharsini

    [/#include <iostream>
    #include "stdafx.h"

    int add (int x, int y)
        return x+y;

    #include "stdafx.h"

    using namespace std;
    int add(int x,int y);

    int main ()
        cout<<"the result is: "<<add(0,9)<<endl;
        return 0;

    Hi..  when I try to run this code, I am getting "fatal error C1083: Cannot open include file: 'stdafx.h': No such file or directory" error when stdafx.h is included in the add.cpp. if the remove this then the program runs fine. Please help me solve this issue

    • nascardriver

      Hi Priyadharsini!

      Remove the includes for stdafx.h and disable precompiled headers in your project settings.
      stdafx.h is there to speed up compilation, but if it causes any trouble I suggest you to simply disable it.

      • Priyadharsini


        Yes. The code works fine when I remove stdafx.h. Thank you.

        But any idea why the error is produced? I am trying to understand the scenario.

        • nascardriver

          I don't know, it's Visual Studio stuff and I don't use Visual Studio.

        • Alex

          Visual Studio has precompiled headers on by default. Those use the stdafx.h header. Visual Studio should create this file for you when you create the project.

          • Priyadharsini


            So do you mean, writing the header in my code will be redundant? And that is the root cause for the issue

            • Alex

              1) If you're not using Visual Studio, you should remove #include "stdafx.h", as you don't need it.
              2) If you're using Visual Studio, you should generally keep #include "stdafx.h" for now. If you're still getting the error, make sure there's a file in your Solution Explorer under the Header Files folder named stdafx.h. Mine looks like this:

  • A few people (including myself) had difficulty trying to figure out how to add another file and compile it together with main.cpp when using Xcode. I just figured it out, and it's pretty simple, so I thought I'd explain it here.

    First, you need to create the new file by going to File -> New -> File. . .
    Then, select macOS and C++ File, then hit "next."
    Then, name the file add.cpp or whatever.
    Uncheck "also create a header file." (I'm not even sure what that does.)
    Now you want to hit "create," but make sure you're in the correct project. You want both of these files to be in the same project.
    Once you do that, it adds your new file to your project, so you can write your code in there and save it. You'll see both files in the menu on the left, and you can toggle between them by clicking on them.
    Once you've saved all the code in both files, then you can compile like normal. I just hit that play button in the upper left. It worked for me.

  • Samira Ferdi

    Hi Alex! you said in the previous lesson that we have to make sure that single file is correct. But, how can I compiles and links that single active files in the active project individually?

    By the way, your website is very cool!

    • Alex

      > Hi Alex! you said in the previous lesson that we have to make sure that single file is correct

      I'm not sure I quite understand what you're getting at. Each individual file in a multi-file program must compile independently.

      > But, how can I compiles and links that single active files in the active project individually?

      There's no need. When you compile your program, the compiler will compile and link each file sequentially. Files may be compiled in any order, which is why each one needs to be independent.

      • Samira Ferdi

        Thank you, Alex. I appriciate that. Will you build a GUI programming using c++ tutorial someday?

        Then, what's the different c++ with objective-c?

        • Alex

          Someday is a long time, so maybe... but it's not likely to happen anytime soon. Any writing time I have is more likely going to go into C++ fundamentals, which don't include GUIs.

          Objective-C is an extension to C (not C++) that was adopted by Apple. I believe there's an Objective-C++ as well. My understanding is that Objective-C has largely been replaced by Swift, but this isn't my area of expertise so I may be misreading the tea leaves here.

  • OTheB


    I've been trying to wrap my head around multiple files in a project for days now, and finding this answered all my questions and solved just about all of my problems!

    I'd like to ask though, what things need to be done so I can define a class in another file along with all its methods, then be able to instantiate it in main.cpp?

    I've managed to get my errors down to 1 which I'm pretty pleased with. I have a file "class.cpp" in which I'm defining a class "thingy" and an object "thing", and this class has a variable "x" and a method that just returns x. It also has a constructor with sets x to 3. In my main.cpp file, I'm declaring the class with "class thingy ;" and declaring the object with "thingy thing ;". The error I get is this:

    I tried putting in declarations of each attribute and method in main.cpp and that game me a multiple definitions error for the class. I then tried swapping out the class definition in class.cpp to just the methods prefixed with "thingy::", but that gave me a "thingy undefined" error, so I forward declared "class thingy ;" in class.cpp and now the errors are just piling up again.

    Will I need header files to separate off classes? If so, then I'm basically back to square one where I have about 50 errors and have no idea what I'm doing.

    Thanks for any help.

    • nascardriver

      Hi OTheB!

      What you need are header files (Lesson 1.9).

      After lesson 1.10a you'll be able to do it like this:




  • Sir i am using dev C++ so say me the procedure to run and see the multiple programs in dev C++ compiler.
    sir which is the best compiler to practice c++ ?

  • Shaheen

    Hi, I am using Visual Studio 2017, things worked well for me. Super helpful tutorials! I have one question though; when it comes to saving the program, do I have to save main.cpp and add.cpp separately or is it just fine to save main.cpp alone and the file that was added to this project (add.cpp) gets automatically saved?

    • Alex

      You need to save main.cpp, add.cpp, and your project file.

      If you try to close add.cpp or your project file without saving first, your IDE should ask you if you want to save. So in practical terms, this isn't something you'll likely need to worry about.

  • Federico

    Hi Alex, your C++ course is simply wonderful.
    I'm using Visual Studio Express 2015 for Windows Desktop.
    The problem is I can't add a new cpp file to the project because the list "Installed" in the "Add New Item" window is empty. There is no "C++ File (.cpp)" item. Do you know how I can restore missing file templates?

    • Alex

      That's odd. I have no idea. Try doing a google search and see what you come up with.

    • Cosmin

      I have encountered the same problem. All you have to do is to go to C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\VCProjectItems_WDExpress and change the name from VCProjectItems_WExpress to VCProjectItems. If your Microsoft Visual Studio 14.0 folder doesn't contain the VC folder (I had this problem), just find the VC folder in the Program Files(x86). There you will find VCProjectItems_WExpress.

  • April

    Hi Alex!

    I've successfully compiled and ran programs with files that contain simple numerical functions. However, when I try to use "std::cout" in a another file, I get an error that reads "'cout' in namespace 'std' does not name a type."

    Any suggestions?

    • Alex

      1) Try your program with an online compiler and see if it works. If not, it's your program. If so, it's your compiler/IDE.
      2) Make sure you're including <iostream> (not iostream.h)
      3) Make sure you're using a modern compiler.

      • April

        1. How do I compile/link multiple files using an online IDE? At the moment, I am trying to do this on

        2. Do I need to #include <iostream> in every file, or just main.cpp?

        3. I am using Code::Blocks 16.01

        • Alex

          1) Most online IDEs don't treat each file as a separate program. I'm not sure whether any of them support multiple files linking into the same program. Try opening a bunch of different ones and see.
          2) You should #include in any file that uses functionality defined in the iostream header. This could be multiple .cpp files, or even .h files.
          3) Ok.

  • YI

    Dropping a quick thank you! Excellent tutorial so far.

  • David

    Hey Alex,

         I'm having trouble getting an output from this project.  I have two files, main.cpp and add.cpp, just like you have showed.  When I press F9 it does't show anything and I'm given the error message " 'endl' is not a member of 'std' "  I even copied the exact code from the examples. Please help!


  • Karl

    Dont know if it is just me but in the newest version of visual studio the solution explorer defaults to folder view, and when you try adding the add.cpp it wount be added to the project correctly. you need to change it to the other view and then add it to source iles

  • Jeremiah

    I'm using 2017 Xcode, and I can not figure out how to add a file and get it to build correctly. When I think i've added add.cpp to main.cpp it fails to compile, even when I forward declare add(). If anyone has figured it out on this IDE i'd greatly appreciate the help.

  • Adam

    Hi, anyone know how to make/add files to a project in Sublime text? I am able to make a project but then I cannot add files to it and stuff. I want to get the example provided working. Any help is greatly appreciated!

  • David

    Hi Alex. I'm not sure if this particular statement you make in the "Something went wrong!" section is valid:

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

    In the next section, you state that:

    Most naming collisions occur in two cases:
    1) Two files are added into the same project that have a function (or global variable) with the same name (linker error).
    2) A code file includes a header file that contains an identifier that conflicts with something else (compile error). We’ll discuss header files in the next lesson.

    If we were to insert the contents of add.cpp (including the definition of the add function) into main.cpp, then both cpp files would contain a definition of the add function. I agree that both files will compile fine, but wouldn't the duplicate definitions cause a linker error?


    Also, I don't know if this is a typo or not, but in the "A multi-file example" section, the errors say:

    add.cpp(10) : error C3861: 'add': identifier not found
    add.cpp(15) : error C2365: 'add' : redefinition; previous definition was 'formerly unknown identifier'

    It doesn't make sense for the 'add' identifier to not be found in the add.cpp file. Additionally, the line numbers seem a bit off.

    • Alex

      Yes, if you #include add.cpp from main.cpp, and both add.cpp and main.cpp get compiled, you'll end up with multiple definitions for everything in add.cpp, which will cause a linker error. So don't do this. :) If there's an inconsistency somewhere in what I said, I'm not seeing it.

      I fixed the line numbering and error messages -- thanks for pointing out the error!

  • Mike Hong

    I am using clion instead of visual studio, and I do not have any information how to add files with this version. Please help me out. Thank you.

  • My dear Teacher,
    Please let me report you that
    Last week I downloaded Code::Blocks 16.01 and for create new file in a project should click: File -> New -> File... and on the "New from template" click icon "C/C++ source". Then click "Go". On template "C/C ++ source" click "C++" and then "Next". On the new template "C/C ++ source" click "..." and on the new template "Select filename", type after "File name" the name only. By trial and error I found that Code::Blocks automatically add the extension .cpp. Then in template "C/C ++ source" click "All" (it means both Debug and Release) and then "Finish". Then on editor's area type or copy and paste the code, and eventually press F9 for compile and link. Output is the expected. Is it okay?
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me ask: how can I find command line in Code::Blocks?
    With regards and friendship.

    • Alex

      Code::Blocks doesn't have a command line in the sense you're talking about. You use the command line when you're working without an IDE.

Leave a Comment

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