Search

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:

add.cpp:

main.cpp:

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.

Conclusion

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

323 comments to 1.8 — Programs with multiple files

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

      main.cpp:

      add.cpp:

      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

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

    int add (int x, int y)
    {
        
        return x+y;
    }]

    main.cpp
    #include "stdafx.h"
    #include<iostream>

    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

        Hi,

        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

            Hi,

            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

    Hello!

    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:

      class.hpp

      class.cpp

      main.cpp

  • 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 https://www.codechef.com/ide

        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!

    David

  • 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

    Hello,
    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]