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

275 comments to 1.8 — Programs with multiple 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 C++ code inside [code][/code] tags to use the syntax highlighter