1.8 — Programs with multiple files

As programs get larger, it is not uncommon to split them into multiple files for organizational or reusability purposes. One advantage of working with an IDE is 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.

Adding files to your project in Visual Studio

In Visual Studio, right click on “Source Files” in the Solution Explorer window on the left, 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.

When you compile your program, the new file will be automatically included, since it’s part of your project.

Adding files to your project in Code::Blocks

In Code::Blocks, go to the file menu and choose “new file”. Give the new file a name (don’t forget the .cpp extension), and Code::Blocks will ask you if you want to add it to the active project. Click “Yes”. Note that you will also have to click the “Release” and “Debug” checkboxes, to make sure it gets added to both versions.

If Code::Blocks doesn’t ask you whether you want to add the file to the active project, or if the file doesn’t show up in the project pane, you’ll need to add it to the project manually. To do so, right click on the project name in the project pane, choose “Add File”, locate the file you just created, and add it to the project.

Now when you compile your program, the new file will be automatically included, since it’s part of your project.

If the new file isn’t compiling or linking with Code::Blocks, make sure the file is set to compile and link. To do so, right click on the file in the project pane, and choose “Properties”. Under the “General” tab, you should see checkboxes that control whether the file is compiled and linked. Make sure they are checked.

Adding files to your project from the command line

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

Now, consider the following multiple-file program:



Try compiling this program for yourself. You will note that it doesn’t compile, and it gives the same compiler error as the program in the previous lesson where the functions were declared in the wrong order:

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

When the compiler is compiling a code file, it does not know about anything in other code files, or remember anything it has seen from previously compiled code files. In this case, when compiling main.cpp, it doesn’t remember that it previously compiled function add() in add.cpp, so it complains that doesn’t know what identifier add is.

This limited visibility and lack of memory is intentional, so that files may have functions or variables that have the same names as those in other files without causing a naming conflict. We’ll see an example of this in the next lesson.

However, in this case, we want main.cpp to know about (and use) the add() function that lives in add.cpp. To give main.cpp access to the add function, we can use a forward declaration:

main.cpp with forward declaration:

Now, when the compiler is compiling main.cpp, it will know what add() is. 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 in main.

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. 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. If you’re using Visual Studio with precompiled headers, every code file needs to #include “stdafx.h”. This includes both main.cpp and add.cpp.

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.


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.

1.8a -- Naming conflicts and the std namespace
1.7 -- Forward declarations and definitions

306 comments to 1.8 — Programs with multiple files

  • 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

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