Search

2.8 — 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.7 -- 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 using a forward declaration for add.

Now let’s take a look at a similar multi-file program:

add.cpp:

main.cpp:

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 for 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. While it may compile and run for this simple example, you will encounter problems down the road using this method.

Summary

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.9 -- Naming conflicts and the std namespace
Index
2.7 -- Forward declarations and definitions

365 comments to 2.8 — Programs with multiple code files

  • Adele

    Hi

    I am running this on my Mac. I get the message when I compile with "g++ -o main main.cpp"

    Undefined symbols:
    "add(int, int)", referenced from:
    _main in ccgnrmBk.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status

    What is wrong?

  • villain222

    ok. i found my problem with code::blocks. whatever your second file is, you just have to goto the left tree window and right click your file (not the main) pick properties goto build tab and make sure compile and Link boxes are checked as well as the debug and release. once i did that I had no problems. why it wasn't already set? not sure.

  • Chip

    Hi.

    I was trying to declare some struct types and enum types along with a few variables (of those types)in a separate file. In the header file I've just included declaration of the variables with the extern keyword. (Yes, I'm using global variables, but I'm new to C++ and i couldn't figure out any other way. Besides it's not that big of a program to be that difficult to track down the variables.) But when the compiler gets to

    #include "buildings.h" //the header file

    it gives an error because it doesn't recognize the structs I've declared in the separate file as types. If I declare the types in the main file before the line

    #include "buildings.h"

    it's all OK, but my idea was to keep the whole program somewhat clean so the types declarations and the variables of that types to be in the same separate file.

    Is there something I could do to make the whole project easier to understand by keeping the variables and their custom made types (structs, enums)in one file and each function in a separate file, without having to crowd the main file code with type declarations?

    P.S. Great lessons. Very comprehensible.

  • Bram Verspeek

    I have a question related to the multiple files programs.
    Is it possible to define a value in the main program and use it in a function without supplying it as an argument?

    Say in main.cpp I have

    int a = 4

    and then in math.cpp I have

    if i run code with this it prints a = 0 instead of a = 4. Is it possible to do this? basically declare global variables that apply in every party of the program? I read a bit on so would a #define do what I want?

  • Jack

    Hi Alex, thanks so much for this tutorial, it's been really helpful so far. I've run into some kind of problem though. When I tried compiling this file I got the following error message 26 times
    Main.cpp(9) : error C2784: 'std::basic_istream &std::operator >>(std::basic_istream &,unsigned char &)' : could not deduce template argument for 'std::basic_istream &' from 'std::ostream'
    1> G:ProgrammingMicrosoft Visual C++ 2008 ExpressVCincludeistream(1021) : see declaration of 'std::operator >>'

    I tried messing around with the programme and I think it's something to do with iostream, I went back and tried to do a simple programme again and I had the same problem. Any idea what's going wrong? I'm using Microsoft Visual by the way.

    THanks!!!

    • D Barber

      if thats a correct copy of the message, it should be 'iostream' and you must have put 'istream' in your code, not sure if thats all thats wrong though.

  • retro-starr

    I get "[Linker error] undefined reference to `add(int, int)'" and "ld returned 1 exit status" as errors in dev-c++.

    It's weird because if I use g++.exe (found inside the directory of dev-c++) it compiles and runs just fine...

  • Tyler

    Hi, I know this may sound stupid but i'm brand new to c++ an I cant seem to find Source files on my MS visual 2005 express addition please let me know where they are.

  • Luke

    Hey,

    I'm using Code::blocks 8.02, and it won't let me add any files to the active project. I can see the box which says "Add file to active project" but it won't let me check the box. I don't even get the option to release or debug.

    I have tried making everything .cpp, but nothing changes.

    Any thoughts? Does it have something to do with the fact that my 'active project' is just the default workspace.

    If there is a manual way to add files to an existing file I would be thrilled.

    Any help/thoughts are appreciated, and thanks heaps for these tutorials!

    Luke

  • Michael M

    Thanks! Followed the tutorial and it works!

  • alexandra

    Hey , I added the two files in a project. I use Dev-C++ and when compiling I receive this error:
    Circular maimulte1 <- maimulte1.o dependency dropped.
    Circular maimulte2 <- maimulte2.o dependency dropped.
    G:\c-compiler\Dev-Cpp\LUCRU\Makefile.win [Build Error] [Proiect1.exe] Error 1
    Can you please help me?

    • baldo

      `Circular xxx <- yyy dependency dropped.'
      This means that make detected a loop in the dependency graph: after tracing the prerequisite yyy of target xxx, and its prerequisites, etc., one of them depended on xxx again.

      Maybe you have included the cpp files and made a loop or something.

  • sam

    Sorry to post so much. But I experimented and figured it out. it was in the interface. its buggy. when I added add.cpp it showed add to project and ask for check release and debug which I did and made sure ended in .cpp. but I then notice when i rotated my code to one file it worked..so knew the 2nd file even though it was showing was not adding to the compilation. then i noticed when i brought up tree it was light grey on the text. So i deleted it..and clicked add file to project and selected again add.cpp and it became not greyed out on the list...

    now it compiles and works perfect in a 2 file format.

    Best Regards

  • sam

    below is the code lead with the file name:

    main.cpp

    here is the code in 2nd file

    add.cpp

    I am using codeblocks on kde 4.3 kubuntu with new gcc++ 4.4 and i have added file "add.cpp" to project and checked marked debug and release.

    when i compile the code with the compile button I get this message

    -------------- Build: Debug in Lab1 ---------------

    Linking console executable: bin/Debug/Lab1
    obj/Debug/main.o: In function `main':
    /home/blahblah/C++ LEARNING LAB/Lab1/main.cpp:8: undefined reference to `add(int, int)'
    collect2: ld returned 1 exit status
    Process terminated with status 1 (0 minutes, 0 seconds)
    1 errors, 0 warnings

  • Sam

    This is not working for me either.

    I have both debug and release checked. and files main.cpp and add.cpp and cut and pasted code. but when I compile it stops and gives this error on the line where the cout is located in main.

    obj/Debug/main.o||In function `main':|
    /home/blahblah/C++ LEARNING LAB/Lab1/main.cpp|11|undefined reference to `add(int, int)'|

    sure its something I am doing wrong. But I cannot figure it out

    I have codeblockers on linux and up til now I have not had a problem.

    Best Regards

  • tekktronic

    Awesome tutorial!!

    Clean, clear, and concise. Much appreciated, Alex... I've been looking for something like this for quite some time now, and I have to say, I recommend your tutorial to anyone who wants to get at C++!! Anyway, I have several questions:

    1. I'm using Code::Blocks 8.0.2, and I was wondering if there was a way to actually get it to save files as .CPP files automatically, that way, the compiler doesn't trip out everytime a .C files gets put in a project.

    2. Why does the code (matching the code you have above [complete with forward declaration] verbatim, by the way) NOT input what it's supposed to output ("The sum of 3 and 4 is: 7") It compiles and runs, but all I get is "press any key to continue" without the specific output (NOT EVEN THE NUMBER 7!!) Is there a cause for this, and how can I fix this??

    3. Do I have to #include to add.cpp, also??

    Thank you kindly for all your efforts!! Kudos!!!

    -tekktronic-

  • Keeks

    I am using CodeBlocks 8.02 in a Mac with Leopard, It is working nicely, until this lesson, when I created a new file as described above it never showed the configuration (the auto tabs and colors) and besides that I weren't able to build the project. I was trying different approaches to solve this to no avail. Finally the only thing that was needed was to append the extension when creating the file ( .cpp ), after that it worked like a charm.
    Alex, you have made an extupendous work with this Learning Center.
    Keep the great work.

    Keeks

  • Pratik Shivarkar

    Great, Im using Code Blocks and MonoDevelope on Linux
    This tutorial works like a charm.

  • devin

    I do every thing you ask me to and it keeps saying that i messed up saying unexpected end of file while looking for precompiled header and yes i do have the #include "stdafx.h" in the text please help me.

  • Aidan

    Hi All

    Excellent Tutorial this ....

    However when I try to compile and run the main.cpp file ..I get the following error...Both main and Header files are created exactly as they are on this page , with stdafx.h declaration added in the main.cpp file..

    I am using Microsoft Visual Studio 2005

    The error I get is

    >main.obj : error LNK2019: unresolved external symbol "int __cdecl add(int,int)" (?add@@YAHHH@Z) referenced in function _main

    Any help would be hugely appreciated..

    Best Regards

    Aidan

  • Mina

    If I don't add

    to the beginning of the second file (io.cpp) code::blocks complains and says that 'cin' is not defined. If I do include it then everything works fine. What might be happening?

    • I am not sure which file you are talking about. However, iostream is the header file that defines what cin is. If you do not #include it, the compiler does not know what cin is and will complain.

  • David

    These two statements you have made don't seem to agree:

    In the tutorial:
    "When the compiler is compiling a code file, it does not know about the existence of functions that live in any other files. [this sentence-->] This is done so that files may have functions or variables that have the same names as those in other files without causing a conflict."

    In your comments:
    "If you have the same function declared in multiple files and you try and link those files into the same project, the linker will complain that it doesn’t know which version of add() to use."

    So which is it? If the compiler complains about having multiple files in the project containing the same function names, then your first statement (tutorial statement) is not true -- there is in fact a conflict.

    • Both statements are true.

      The compiler does not know about functions that are defined in other files (unless you use a prototype).

      However, if you have functions with duplicate names in different files (which the compiler will not complain about), the linker will complain, because it doesn't know which one to resolve the function call to.

  • sir,
    how i can compile & run a c++ file in command prompt...plz tell me.

    • csvan

      if you are using Linux:

      g++ myFile.cpp -o myProg

      where myFile.cpp is the name of the source file. myProg will be the name of the resulting program. You run it by typing ./myProg

  • Tony

    How do you use multiple files if you're not using Visual Studio? I'm using g++.

  • adam

    What if you have int add() in multiple other files. eg. add1.cpp and add2.cpp and main.cpp calls it, will it call the int add() from add1.cpp or from add2.cpp?

    • If you have the same function declared in multiple files and you try and link those files into the same project, the linker will complain that it doesn't know which version of add() to use.

  • 13eastie

    I am using a command-line compiler (I have tried g++ and borland's bcc32).
    I have both of the .cpp files in the same folder.
    Neither of them will compile.
    I'd be very grateful if you could tell me why not.

  • zack

    A little message to anyone using codeblocks, when creating the new add file it asks you to enter the file's name and location. You have to check the debug and release boxes which appear just below this (although which you need to check depends on the build target I suppose) otherwise it won't work. I was trying to figure out why it wasn't working and from the comments above it seems that I'm wasn't the only one :-)

    • Paul

      I'm going to have to verify Zack's last comment. With code blocks ide I was unable to compile the files without checking the debug and release box option when creating a new file. I would suggest noting that in the tutorial, it was a bit frustrating trying to figure out why my files could not compile correctly when the code was identical to what was posted in the tutorial.

      Thanks , Paul

  • buck

    Hi
    I'm a computer hobbyist and have been exploring C++ as a passtime.
    I have tried all the C++ tutorials I could find over the past few years and I consider this tutorial superior in all aspects from the quality of the content to your approach to teaching the subject.
    I have written and successfuly compiled the project in this section but find it does not output the result (7) to the screen. Should it?
    I should mention I'm using MS Visual C++ 2008 Express.

  • liu

    So if I write down a forward declaration, this can refer to an other file, that's clear..
    but what if this file is not in the same folder where the main-file is?
    (e.g. i put add.cpp, sub.cpp, mult.cpp, divi.cpp into the folder 'math')
    i can't try it out on myself this week, someone has to tell me that.

  • Rather interesting. we are getting further and further into this. I think you are doing a very good job thus far.

  • Attila

    Just 1 additon: Maybe it has been mentioned before, but for the MS Visualblablabla, you need the

    in every single file...

    • john

      Same here! This must be mentioned on this great tutorial!

    • Catreece

      Yay, I was correct then! I just added it out of reflex because I assumed that the computer would be too stupid to know what to do with anything if not specifically hand-fed the instructions in every single case.

      I was not disappointed. =P

      Still, I can see that being handy. It'd mean that individual files can each reference specific different libraries, which probably cuts down on overlap of names by a large margin. If the audio and video libraries have overlap, but you have a video function and an audio function both as their own, separate files, then each individual file can only load up the libraries they specifically need to run, and there won't be a naming conflict that way.

      I'm starting to think the motto for C++ should be "trust the programmer, but only trust whoever wrote the library as far as you can throw them."

      • Darren

        Computers are stupid, they cannot think for themselves; it is the programs that instruct the computer on how to operate. Therefore a computer is only as clever as the human who programmed it.

        The "stdafx.h" header is only required when using the pre-compiled header nonsense ..er.. option in a VS project. When creating a project in VS select an 'Empty Project' so as not to have to deal with the "stdafx.h" rubbish.

    • Felipe

      Or.. you can go to project->properties->Configuration Properties->C/C++->Precompiled Headers->Precompiled Header->Not using precompiled headers.
      Then you wont need to add

      .

Leave a Comment

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