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

278 comments to 1.8 — Programs with multiple files

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

    • Alex

      If it works, then it’s okay. 🙂

      • My dear c++ Teacher,
        Please let me point out that "If it works, then it’s okay", is not a rule. For example, programs with "using namespace std;" work fine but you suggest not that, but "std::".
        With regards and friendship.

        • Alex

          I didn’t mean that as a general statement, I meant it as applied to your specific situation, since I can’t verify that your steps work myself. But I don’t see anything weird, so it seems fine.

  • 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 C++ code inside [code][/code] tags to use the syntax highlighter