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:

add.cpp(10) : error C3861: 'add': identifier not found
add.cpp(15) : error C2365: 'add' : redefinition; previous definition was 'formerly unknown identifier'

When the compiler is compiling a code file, it does not know about the existence of functions that live in any other files. This limited visibility 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

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

208 comments to 1.8 — Programs with multiple files

  • 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

      .

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

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

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

  • 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

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

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

  • Tony

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

  • 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

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

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

  • 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

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

  • Pratik Shivarkar

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

  • 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

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

  • 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

  • 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

    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

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

  • Michael M

    Thanks! Followed the tutorial and it works!

  • 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

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

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

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

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

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

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

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

  • bitpoint

    It should probably be mentioned here that #include “stdafx.h” should be placed at the top of each file as the program did not compile without it. I had assumed incorrectly that the compiler would simply include whatever was on the main function file for each file. I’m assuming if you want to include anything else it must be placed at the top of each file.

  • Babysabre

    I’m using Code::Blocks and it’s complaining about multiple definitions:

    • jonathan.mclaren

      I am dealing with the same error.

      It resolves when I add the add() below the main(), though the point of this is to rely on add() in a separate file. I would greatly appreciate help with this.

  • pshetty

    for those of you who faced linker errors, the reason could be that you did not add the iostream header file in your cpp file where you have defined the function

  • marki123

    i have put in the code for both files in to code blocks exactly. \(main and add)
    but when it comes to compiling it it seems fine with the code but give the warning message.
    “WARNING: Can’t read file’s timestamp: C:\Documents and Settings\Desktop\multi-file programs\Untitled1.c
    Linking console executable: bin\Debug\multi-file programs.exe
    mingw32-g++.exe: obj\Debug\Untitled1.o: No such file or directory

  • socal93

    I couldnt get this to run….. When i compile the the two files i get a error saying ” Undefined reference to add(int,int) ”

    I have the code set up all the same as yours. Im assuming that the compiler doesnt see add.cpp.

    Im using code::blocks.

    • Elphie

      I had the same problem with Code::Blocks. I fixed it by recreating the file, only this time under “Add file to active project in build target(s):,” I checked both Debug and Release, which for me are always unchecked by default.

  • ionman101

    I found out why it isnt running on codeblocks (atleast on my computer). When you open a new file for the project, it creates the file with just *.c instead of *.cpp. Try saving the new “add” file with .cpp at the end. I did that and it ran with no errors

    • 4713N

      I just added #include “add.cpp” and it works.
      I’m using code::blocks

      • rameye

        You can do it that way, but that defeats the purpose of a multiple file build. Using #include just makes the preprocessor copy and paste the contents of a different file into main.cpp, and main.cpp will still be the only file compiled afterward.

        What you need to do is make your IDE aware of the second file by adding it into the project you have open, which previously was only a single file project. When you create the second file you need to do it using the IDE “New file” and select “Add to project” or something relevant to that. If your IDE shows a tree structure of project files, your new file should then show up in it.

        When you do this you make the IDE configure itself to use the new file when it builds the project into an executable.

        I use NetBeans but I think all IDE’s work the same in this regard, although the terms they use in menus and such may be different from one to another.

  • Cleverlegs

    main.cpp

    add.cpp

    It doesn’t seem to work without the stdafx.h file in add.cpp, is that right?

  • Benny The Wah

    I’m using Code::Blocks 10.05 and I have done everything in the tutorial but it didn’t work. Eventually I resorted to copying and pasting the main.cpp with the forward declaration and the add.cpp from this tutorial. they are both in the same project folder but when I try to compile them it comes up with this error in the build messages area:

    obj\Debug\main.o||In function `main’:|
    C:\Documents and Settings\Benoit\My Documents\C++ Projects\Practising\Multiple Files\main.cpp|8|undefined reference to `add(int, int)’|
    ||=== Build finished: 1 errors, 0 warnings ===|

    • andreigc

      I’m using Code::Blocks 12.11 and I had the same problem. The problem was that the add.cpp file was not added to the C::B project(.cbp file) although it was created with the C::B editor.

      One solution:
      Right click on the project in the editor and select “Add files”. After that navigate to the project’s folder and select “add.cpp” and click Open.

      Hope this might help someone dealing with the same issue in the future.

  • therry1

    I have completed everything up to section 1.8 (multiple files) with no problems… (however, I have not used the precompiled header files), but section 1.8 has me totally confused. I understand that the two files are supposed to be add.cpp & main.cpp. However, I do not see add.cpp as a complete file. It looks like simply the defining of a function that is placed before the main function… or a forward declaration of a function. I have no idea how to combine the two as two independent files into a single program.
    Secondly, what is Code::Block? …How is it used?…Where can I find it and its info? Is there a site that will give more data on the subject?

  • jojk

    I have a question. How does the compiler know what to pick add.cpp. I am learning C++ and I’ve learned that you need forward declarations in any and all situations. Multiple files or not. At the top of the code are the declarations (prototypes), then the main file which utilizes functions, then after the main you include definitions of functions. The compiler goes in order, first sees the prototypes and knows the function is defined somewhere and then goes to the main, when that function is called the compiler proceeds through the source code until it finds a function with a matching name and parameter list. It then carries out that function with the parameters passed to it in main.

    What does the compiler do when the function is not defined in the same source code as its call and prototype. Does it look in the current directory for source code files with the same name as the function? Does it look at all the .cpp files in the current directory for anything that has a function with the same name and parameter list? By what magic does the compiler know what file contains the function definition when it leaves the source code that calls the function?

    Why doesn’t anyone else have this question?

    • numberneyen

      Hi I’m brand new to C++, but I did have the same question, and with some messing around this is what I’ve found to be apparently the case, although this is merely from observation and not from any teaching or really foundational knowledge (I could be wrong):

      Also be aware that I’m not 100% if the error is with the compiler or the linker, so while I write “compile”, it may actually be a linking issue. Still, I give a little solution 😛

      The project won’t compile if there are multiple functions of the same name with the same number/type of parameters in any of the files. For example, let’s say you have main.cpp which includes the function “int add(int x, int y)” and addxz.cpp which includes the function “int add(int x, int z)” in it. Despite the different names given the parameters inside the function in addxz.cpp, it is an int function named add() which requires two parameters, and so the project will not compile; there is no magic way for the compiler to tell the difference between the two functions. The solution? More specific names, i.e. call the function in addxz.cpp “int addxz(int x, int z)”. This clarifies the code for both the reader and the compiler.

    • rameye

      Think of the IDE as a machine that keeps track of a collection of source files that need to be compiled and linked together into one executable.

      The collection of source files along with project configuration files and generated ‘make’ files is what is called the project.

      The compiler and linker that is used by the IDE is whatever you told it to use when you initally setup the IDE. The compiler and linker are separate runnable programs on their own, you can use them from a command line without ever using an IDE in the first place.

      What the IDE does is automate for you all the typing that you yourself would have to do on the command line to compile and link all those files, and in a big project with lots and lots of source files buried many directories deep, that would quickly become tedious and prone to error every time you added, edited, or removed a source file from your project.

      The IDE also keeps track of where to put everything neatly on your storage device, and remembers for you where to look again for them.

      What happens when you “build” the project that is opened in the IDE?

      The IDE runs a ‘make’ file that it had previously generated for the project, and that ‘make’ file runs the compiler and linker for you, compiling all the source files and then linking all the object files together into one beautiful executable file.

      The linking step is where functions that live in one file but are called from another file are resolved.

      Compilers and linkers can work with multiple files, the files are just specified as separate arguments when calling the compiler or linker.

      For example, the C++ compiler my IDE uses is g++ and the commands my IDE used to compile and link both main.cpp and add.cpp were:

      g++ -c -O2 -MMD -MP -MF “build/Release/GNU-Linux-x86/add.o.d” -o build/Release/GNU-Linux-x86/add.o add.cpp

      g++ -c -O2 -MMD -MP -MF “build/Release/GNU-Linux-x86/main.o.d” -o build/Release/GNU-Linux-x86/main.o main.cpp

      g++ -o dist/Release/GNU-Linux-x86/cppapplication_1 build/Release/GNU-Linux-x86/add.o build/Release/GNU-Linux-x86/main.o

      The first command compiled the file add.cpp and created a file named add.o (An object file)

      The second command compiled the file main.cpp and created a file named main.o (Another object file)

      The third command told the compiler to use a linker to link both add.o and main.o into an executable file named cppapplication_1

      So you see it is not the job of the compiler to find where the guts of functions live in multiple .cpp files, it is the job of the linker. The compiler makes the guts, the linker finds the guts. All the compiler needs is to be assured by your forward declaration that the function has indeed been fully defined somewhere in one of the .cpp files you specified to it, and it will leave a note in the object file that it generates for the linker (that note being the function signature from the forward declaration), the linker then picks it up and goes looking in the object files for the correct function guts, and places the guts correctly as machine code in the executable file it is constructing. In the spot that you called the function within your C++ source file.

      Beautiful isn’t it?

      • rameye

        When I said “places the guts correctly as machine code in the executable file it is constructing” I meant that it places the machine code for a call of the function, not the machine code of the function. The machine code of the function itself will reside in it’s own spot elsewhere in the executable. Unless you use the inline keyword with the function declaration. But that’s another subject totally.

      • Loganathan

        Very clearly
        explained. Thanks

  • neuronet

    I got it to work just by including the usual headers that were not included in the code snippets in the original post. Let me know if it doesn’t work, I’m sure I won’t have any idea why… 🙂

    main.cpp:
    //First attempt at a project with function defined separately
    #include
    #include
    #include
    using namespace std;

    int add_two(int in1, int in2); //function prototype

    //Main
    int main(int nNumberofArgs, char* pszArgs[])
    {
    int in1;
    int in2;
    int sum;

    cout << "Function Test\n";
    cout <> in1;
    cout <> in2;
    cout << endl;

    sum=add_two(in1, in2);
    cout << "Sum of your guys is : " << sum << endl;
    return 0;
    }

    add_two.cpp:
    #include
    #include
    #include
    using namespace std;

    int add_two(int firstIn, int secondIn)
    {
    cout << "\nIn function \"add two\"\n" << endl;
    return firstIn+secondIn;

    }

  • RetroBoy

    FWIW, I am using VS Express 2012. After creating and saving add.cpp as described above I had to right click on “Source Files” and click “Add” then “Existing Item…”

    This is despite the fact that I had saved add.cpp in the same project folder.

    • rameye

      Yep, that is what you have to do. The IDE does not know a .cpp file is part of your project unless you tell it that. The .cpp file’s existence alone does not make it part of the project.

      • Alex

        If you follow the instructions as specified, and right click on your project and add a new file from there, it will automatically be added to your project.

        If you add a new file from the file menu, it won’t be, and you’ll have to add it manually.

  • lilith

    I tried to compile the multiple file-example using g++ and it doesn’t link. Is it possible that you have to have header files if not using an IDE?

    • rameye

      If you had no problem compiling/linking the single file examples in previous lessons then it’s not missing standard libraries causing it.

      And yes, you need the header files even if not using an IDE. After all they are referenced in the #include directives. And without the #include directives calls to standard library functions are not going to resolve at link time.

      All the IDE does is accomplish for you the same thing you would have to do at a command line yourself without it.

      g++ -o myfile add.cpp main.cpp should have compiled and then linked add.cpp and main.cpp into the executable myfile

      If not, then look at the first error that was given, it will point to a line # in your .cpp file. Take it from there.

      Also try g++ -help or g++ -v -help (that’s two dashes before ‘help’) at the command line, I believe both will give you a list of options you can use with g++, some of them will display the paths to required c++ libraries. And holy cow, there are a ton of options for g++. Best to have an IDE to set them for you after you select human readable options in the IDE project configuration.

  • vgf89

    Hey, author, you forgot to put the line
    #include "add.cpp"
    in your main.cpp file. If you compile with something other than Visual Studio, the linking will fail (I’m compiling with clang++ myself).

    • vgf89

      Nevermind, it seems that running clang++ with both files as inputs works. Still ugly though, I would think that this section and the next section should be one section.

    • Alex

      Generally speaking, you shouldn’t #include .cpp files from other .cpp files.

      While doing so isn’t disallowed, there’s rarely a good reason to do so, and plenty of reasons it should be discouraged.

  • mashiro.ia

    Hi, I find solution.
    In add.cpp, you must have

    #include "stdafx.h"

    at the top.

    My add.cpp is like this:

    #include "stdafx.h"
    int add(int x,int y)
    {
    return x+y;
    }

    and my main.cpp is:

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

    int add(int x,int y);

    int main()
    {
    using namespace std;
    cout << "The sum of 3 and 4 is: " << add(3,4) << endl;
    return 0;
    }

  • Dreadless

    Dont forget to exclude any other .cpp files you may have been working on from the project!! Check your solution explorer and right click on any .cpp files other than main and app and click ‘exclude from project’

  • Ciprian

    I have solved the Error problem.

    Right click on project and then add (add.cpp),then you should have on Sources : add.cpp and main.cpp. Run it and voila !

  • jvanosda

    For those having problems, I did the following:
    main.cpp

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

    int add(int x, int y); // forward declaration using function prototype

    int main()
    {
    using namespace std;
    cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
    return 0;
    }

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

    Mine compiled just fine once I included the add.cpp.

    • rameye

      But you kludged it by adding the #include add.cpp directive.

      The whole point here is to use multiple files when compiling, not copying one file into a spot inside another (which is what #include does) and then still compiling a single file.

      #include should only be used to insert header (.h) file contents, which contain forward declarations of external functions, not to insert other .cpp file contents.

      • Alex

        I agree with this comment. Do not #include .cpp files.

        If your code isn’t compiling, it’s probably because add.cpp didn’t get properly added to your project.

  • Loganathan

    Thanks much Alex for this very good tutorial. The way of introducing and explaining things to the very depth detail is so nice and easy to understand and to follow up. Your tutorial is greatly appreciated.I am sure everyone who ever go through this site will feel the same.

  • imstilllearning

    Here is solution to those who main.cpp cannot access add.cpp.
    -This problem is caused by creating different source file but not in a same project.
    (note - I’m using dev-c++ , but you can figure this out)
    (note - This is for FORWARD DECLARE lesson )

    1. File > Create new project
    - Name the project MultipleFile(for example).

    2. Create new “main” source file under this project
    - Create a source file name main.cpp.

    // #include “stdafx.h” for those using Microsoft Visual C++

    #include
    int add(int x, int y);
    int main()
    {
    using namespace std;
    cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
    return 0;
    }

    - Compile

    3. Create new "add" source file under this project.
    - Create another source file name add.cpp

    // #include "stdafx.h" for those using Microsoft Visual C++

    #include

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

    - Compile

    4. Compile and execute “main” now, and it should work. If problem persist, try to create a new project in a new folder, as you might confused it with other “add” you made before. Or remove other source file first you made before, and then continue with this lesson.

    Hope this help, correct me if I’m wrong.

    p/s : So far, this website teach me a lot of things I did not notice before. Good job.

  • newuserba

    Please Help with the errors I am getting below. I am using Microsoft Visual C++.

    My main CPP program is
    #include “stdafx.h”
    #include

    int add(int x,int y);

    int main()
    {
    using namespace std;
    cout << "The sum of 3 and 4 is: " << add(3,4) <---- Build started: Project: BA PG Dec 17 Start 2 Part1, Configuration: Debug Win32 ----
    2>---- Build started: Project: BA PG Dec 17 Start 2Part2, Configuration: Debug Win32 ----
    2>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
    2>C:\VC2010Projects\BA PG Dec 17 Start 2 Part1\Debug\BA PG Dec 17 Start 2Part2.exe : fatal error LNK1120: 1 unresolved externals
    1>BA PG Dec 17 Start 2 Part1.obj : error LNK2019: unresolved external symbol “int __cdecl add(int,int)” (?add@@YAHHH@Z) referenced in function _main
    1>C:\VC2010Projects\BA PG Dec 17 Start 2 Part1\Debug\BA PG Dec 17 Start 2 Part1.exe : fatal error LNK1120: 1 unresolved externals

  • Tyler

    I am at a complete loss here… typed in EXACTLY what it says above, check ALL the comments for a solution, i have absolutely no idea what is happening. Using Visual Studio 2010.

    Started off with an error message stating that the add.cpp had a error C2447: ‘{‘ : missing function header (old-style formal list?). No idea what that means, tried the few things i know how to do (added some ;’s, put “#include” in half of the functions, etc) nothing at all.

    Now, after the 4th attempt to restart, I get a completely new message stating “LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt”

    Here is my code:

    ______________________
    add.cpp:

    __________________________
    I have #include "stdafx.h" at the beggining of both
    A note is that the "add" parts within the functions are not coming up as blue, just staying black

    Any suggestions? Getting super frustrated on something that is relatively straightforward.

    Also, to Alex, might consider putting down the exact file type you want for the new file (.cpp). Was a bit confused to start there.

    No complaints otherwise. Much appreciated.

  • Khalid

    Hello Alex, thanks for the tutorial. I’m using minGW with cLion, (because i cant find out how to get visual studio to work, I’ve had it before on another computer, first time I was doing this tutorial) and when i add a new file all it asks for is a name, and when I add it its blurred on the files list to the right. When i run the code I get

    C:/Users/Khalid/Documents/C++/Projects/Hello/main.cpp:7: undefined reference to `add(int, int)’

    Please help, I’d really like to continue this tutorial. Thanks.

  • Likith C

    My first simple add program, I’m running it on Visual studio 2013 and well I’m using “Using Name Space std” globally. Last but not the least tutorial is the best.

  • amin

    how different are the other languages?
    thank you

  • Amin

    yes
    and python and matlab and fortran?

    right now im kinda dizzy
    witch languages are better to do what kind of things
    there are so many languages !and i want to be a perfect programer
    help me!!!

  • Juan Diego

    Hi
    I have both files with the #include "stadfx.h" as the top line, but when I try to compile, it gives me the error: Cannot open the source file "stadfx.h". Why does this happen?
    Thanks for your response and the tutorial, it's great.

  • Chris

    Quick question Alex, my program ran smooth as butter using two files to do so. I included the #include "stdafx.h", but I’m wondering, even though it worked here just fine should I #include <iostream> in each file as well?

    • Alex

      You should only #include if you use any of the things that iostream defines (namely, std::cout, std::cin, or std::endl).

      If you’re not using any of these, then you don’t need to #include .

      One easy way to tell whether you need it is to comment out the #include. If your program breaks, you need it. 🙂

  • Eason

    Since the program is always starting with the main function, why there is no main function in add.cpp?

    • Alex

      Programs can only have one main() function. For multi-file programs, such as the example above (which has add.cpp and main.cpp), main() only needs to exist in one of those files.

      In the add example, execution starts at the main() function in main.cpp. On line 7, it makes a call to add(), which happens to be defined in a different file (add.cpp). Then main() returns 0 back to the operating system, and our program is finished.

      There’s simply no need for a main() function in add.cpp.

  • Thank you for an excellent tutorial, Alex.

    Your hard work and commitment is greatly appreciated!

  • whats the difference between void main and int main?

    • Alex

      A void return value means the function doesn’t return anything to the caller. In the case of main(), the caller is the operating system.

      The C++ specification says that main() must return an integer, so void main() is technically illegal in C++.

      However, many compilers allow it though (they just internally convert the void to an int, and return 0).

      Generally, you should avoid using a void return value on main, as some compilers may not accept it.

  • Joe

    Im having trouble compiling.  I am using windows visual studios.  

    This is what I have written, and am trying to compile, but I keep receiving mulitple errors such as…

    Warning    1    warning C4627: ‘#include "stdeafx.h"’: skipped when looking for precompiled header use    e:\c++\consoleapplication1\consoleapplication1\add.cpp    1    1    ConsoleApplication1

    Warning    2    warning C4627: ‘#include <iostream>’: skipped when looking for precompiled header use    e:\c++\consoleapplication1\consoleapplication1\add.cpp    2    1    ConsoleApplication1

    Error    3    error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include "stdafx.h"’ to your source?    e:\c++\consoleapplication1\consoleapplication1\add.cpp    8    1    ConsoleApplication1

    Error    4    error C3861: ‘add’: identifier not found    e:\c++\consoleapplication1\consoleapplication1\main.cpp    10    1    ConsoleApplication1

        5    IntelliSense: identifier "add" is undefined    e:\C++\ConsoleApplication1\ConsoleApplication1\Main.cpp    10    39    ConsoleApplication1

    The first two seem to happen alot if I try to just code from scratch.  I really have no idea what I am doing and the extent of my knowledge is using codecademy to try and learn javascript which I did not get very far in.  Any idea as to what I did wrong would be greatly appreciated.

  • Atul

    Why am I getting this error?
    Error    1    error C1083: Cannot open precompiled header file: ‘Debug\ConsoleApplication7.pch’: No such file or directory    c:\users\atul ramkrishnan\documents\visual studio 2013\projects\consoleapplication7\consoleapplication7\source.cpp    1    1    ConsoleApplication7

  • Jim

    Alex,
    Using multi files in one project is a bit confusing since it’s hard to understand just what you want us to do here. In this lesson you show main.cpp and add.cpp. But neither one of these functions can be compiled without the other (as shown) or you get errors. (Which you pointed out)

    However the code for each function, can be stored in separate files and located anywhere on a PC. So, I would assume these files were not precompiled and both have been given a .cpp suffix. Is that true?

    I would also assume that every Project must have one and only one, unique main.cpp function that you add new files to in the IDE to build a program.

    Is this what you want us to do? Open a new project and add main.cpp and add.cpp to it and then modify main.cpp so add.cpp will work  Please expand on this.

    What, confuses me is you can’t give code a .cpp suffix until you compile it with Code::blocks. What am I missing?

    • Alex

      Both main.cpp and add.cpp are not precompiled, and they have a .cpp suffix.

      Every project must have a main() function. It can live in any file. I typically put mine in either main.cpp, or <application_name>.cpp just so I know where to find it.

      Your sequence of steps is correct if you want to duplicate the example yourself.

      I’m not super-familiar with Code::Blocks, but it sounds suspicious that it wouldn’t let you put an extension on a file until you compile it. You should be able to put the extension on it when you either create or save the file.

      For what it’s worth, C++ doesn’t care about extensions. They’re more for our use in keeping things organized.

  • Jim

    How to do this in code::blocks (CB) 13-12.

    Make a new project in CB, I called mine MF-Demo, for multi file demo. MF-Demo will include a main.cpp(Hello World).  Click to open main.cpp (Hello world) and cut it’s entire content. (the file is now empty) Copy and Paste main.cpp from this lesson. Now you need to add a new->empty file in CB. Copy and paste add.cpp (from this lesson) into this empty file. Make sure this file is named add.cpp in CB.
    CB should show these file in the editor right next to one another, in the management window they will be listed there to. Now open add.cpp and copy the first line only.(int add (int x, int y) Now open the new main file and paste it above the main.cpp. At the end of this line type in a semicolon. Now you can us CB Build and Run and you should see the results on the console screen….

    Note you can do this in any project but if you do it this way you can delete the entire project later. You could have saved these two file into your PC and copied them from there instead of from this lesson.  I recommend that you print this out and follow it carefully.

    I hope this helps other users.

  • Jim

    Alex,
    This may not be the proper place to bring this up but I stall have questions on Functions. (Move it if you’d like!)

    I’m using code::blocks 13-12 on Windows 64, and it’s geared toward projects not functions. Therefore a function can not be precompiled, debugged or tested before using it in a program without a main function.

    Certainly the pro’s don’t write small programs and then take them apart to reuse a function like: readUserName or getPassWord for instance.

    If I wanted to make functions to add, subtract multiply or divide two variables. How do the pro’s handle the testing, storage and reuse of functions like these without worry?

    • Alex

      Great question, and here is as good a place to ask this question as anywhere. All IDEs are geared towards projects, not functions, because you compile a project (not a function) with the goal of producing a program.

      Typically experienced programmers will create pairs of files (a .cpp and a .h) that contain generic/reusable functions that implement a set of related functionality. For example, a bunch of math functions, or a reuseable list. Once you get into object-oriented programming, this will probably be implemented as a single class.

      Those .cpp and .h files can then be kept in a common location where they can be accessed (or copied into) by multiple projects (with a backup stored in version control).

      It is possible to precompile .cpp files into libraries (either static or dynamic libraries). I cover how to do this in the appendix of the tutorial. This creates a .lib or .dll on windows, or a .a or .so on unix, which replaces the .cpp file (you still need a corresponding .h file).

      Testing functions and classes is a whole subject in and of itself. One common way to test reusable functionality is to provide a unit test or testing application. Essentially this is a small program that exercises each of the functions and validates that they are producing the correct output. The test can be invoked whenever a change is made to ensure the change hasn’t broken anything else.

      So, specific to your case, I’d create a math.cpp with add() and subtract(), and a math.h header that contains the prototypes for add() and subtract(). I might also include a test() function to ensure add() and subtract() work with well known inputs (two positive numbers, two negative numbers, a positive and a negative number) and give the expected results. Then I could include these in any project that needs them.

  • Joseph

    I do not understand how I am overloading a function here.
    I have two files: multiply.cpp and main

    multiply.cpp

    main.cpp

    I get an error on line 7 of main.cpp saying "statement cannot resolve address of overloaded function"

    and I am baffled…lol

    • Alex

      The compiler is actually complaining about endl, because you have a wayward semicolon after multiply(2,3).

      It should be:

  • Freffy

    I cannot figure out what is going wrong with this code.  I am trying to use 3 simple separate files, but it is not working.

    Also I cannot figure out how to get code colored text
    The errors i get are, “syntax error indentifier y”
    “indentifier y is undefined”
    ^ both for line 4 of my main()
    and “too few arguments in function call” in regards to my multiline statement

    • Alex

      You have an extra comma between int and y in your prototype.

      To use the syntax highlighter, put your code between [code][/code] tags. Your closing code tag was missing the slash (I fixed it).

      • Freffy

        Oh!
        I redid the whole program from scratch and was able to get it to work before I got your response!
        I love that feeling when the program does what you expect it to do!
        you are awesome, thanks!!

  • Thomas Keith

    Alex,

    I have a two file project wherein one file is integerInput.cpp and is written like this:

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

    int integerInput()
    {
        int x = 0;
        std::cout << "Please enter an integer." << std::endl;
        std::cin >> x;
        return x;
    }

    It seems to work fine.  My main file looks like this:

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

    int main()
    {
        int integerInput(); //forward declaration (function prototype)

        int x = 0;
        integerInput();
        std::cin >> x;
        
        int y = 0;
        integerInput();
        std::cin >> y;

        std::cout << "The sum of your two integers is :" << x + y << std::endl;

        return 0;
    }

    I end up having to input the integers twice.  It appears that my call to integerInput()is producing a return, but that return is not being used in my next line, which is std::cin x (or y).  My return appears to be discarded and the second time I input the integer is when I assign the value to my variables.  How can I fix this?

    Thanks

    • Alex

      You’ve correctly diagnosed your issue. integerInput() is reading an integer from the user and returning it to main, but main isn’t doing anything with the return value, so it’s discarded. You’re then using std::cin to read in the value you really wanted from integerInput, which is why it’s asking you a second time.

      The answer is simple. Replace:

      with:

      That way, variable x will be assigned the value returned from integerInput.

      Do the same for variable y.

  • Thomas Keith

    Thanks, Alex, that is easy.  Let me run this by you to see if I really get it:

    The variable x can be defined and set to a value in one line, but it cannot be defined and set to a return value on one line?  Or am I just generally confused?

    If just generally confused, just refer me to the section I should reread. Thanks

    Thanks

    • Alex

      All of the above should work.

      You can initialize or assign a value to a variable from any source that evaluates to a value of the proper type. This could be a literal (e.g. 5), a function that returns a value of that type (e.g. integerInput()), or an expression (e.g. 2+3).

  • Thomas Keith

    OFF TOPIC
    btw, Alex, your profile pic - is this your cat?  Is that some kind of carved up fruit skin being worn  as a helmet?  The pic is cute, but I have to say, the cat doesn’t look too happy about it.  If a fruit skin, what kind of fruit?  I can appreciate because wife and I have 3 cats and 3 dogs. It’s a real kennel around here. 🙂
    As always, thanks.

    • Alex

      Nope, not my cat. The pic is an old internet meme. If you google search for “lime cat”, you’ll find it. Know Your Meme suggests that it is actually probably a pomelo, as a lime helmet would be rather small, even for a cat.

  • Thomas Keith

    Alex,

    Googled lime cat.  Didn’t spend much time there because your tutorials beckoned.

    I get it about initializing variables except I’m still dwelling on the unsuccessful

    that doesn’t work, which is exactly why I called it unsuccessful, go figure.

    Isn’t cin a function in <iostream>?  Does it not work because cin doesn’t define the return as an int value?

    I know I’m probably getting too tied up in detail, but I didn’t think to try

    precisely because

    was unsuccessful.

    Thanks!

    • Alex

      Thanks for explaining your thinking.

      When initializing (or assigning a value to) a variable, the right hand side of the equals sign must evaluate to a value that can be assigned to x.

      So, when we do this:

      integerInput() evaluates to its return value (of type int), and that return value cam then be assigned to integer variable x.

      However, when we do this:

      std::cin >> x actually calls a function that looks something like this: istream& operator>>(const istream &o, int &x);

      That probably looks like gibberish to you at this point, but the important thing to note is that the function returns an istream object, which in this case is std::cin.

      So what happens is “std::cin >> x” evaluates to std::cin, and then the compiler tries to figure out how to initialize x with std::cin. But it can’t figure out how to do that, so it throws an error.

      Besides, when “std::cin >> x” is evaluated, it already puts the value the user input into x, so trying to assign the result of that expression into x would be redundant at best.

  • Chris

    I have experiment about #include. I want to include io.cpp file to main.cpp.
    why it get error? is it like copy and paste io.cpp to main.cpp, isn’t it?
    sorry for my bad English and if the question is so stupid.

    main.cpp

    io.cpp

    the error report at code::blocks:
    ||=== Build: Debug in 1.12 Number 1 (compiler: GNU GCC Compiler) ===|
    D:\CBProjects\1.12 Number 1\io.cpp||In function ‘int readNumber()’:|
    D:\CBProjects\1.12 Number 1\io.cpp|4|error: ‘cout’ was not declared in this scope|
    D:\CBProjects\1.12 Number 1\io.cpp|5|error: ‘cin’ was not declared in this scope|
    D:\CBProjects\1.12 Number 1\io.cpp||In function ‘void writeAnswer(int)’:|
    D:\CBProjects\1.12 Number 1\io.cpp|11|error: ‘cout’ was not declared in this scope|
    ||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

    • Alex

      First off, you should never #include .cpp files.

      You’re getting an error because io.cpp is being compiled (because it’s in your project) but it doesn’t know what to do with cout or cin because you haven’t prefixed them with std:: or used a using statement.

  • Andy

    Alex pls, i tried so many times, but i cant figure out how to add that second file and make it work together… i have done everything u wrote, i tried to save add.cpp separately to the folder of that project, but it still cant find it… sry for bothering, but i havent found anybody who could answer me. im using the newest visual studio probably  Visual Studio 2015. thank you for ur time and this tutorial

  • Paulo

    Hi Alex,

    I have been spending a very happy New Year’s Day exploring the uncharted (for me) world of programming and C++.  Great job with these tutorials.  Absolutely top notch.

    But I don’t understand why they don’t reference Microsoft Visual 2015.  I appreciate it is a bit of a fag to update all the examples and it is pretty easy to work it out the differences between this version and 2005, but it does slightly undermine the credibility of your tutorials.  Not a beef, just a friendly comment.

    Anyway back to work and thanks again.  You are brilliant!

    Best wishes, Paulo

  • justin jacobs

    my question is when i go to compile main.cpp an add.cpp i get error

    /buildsources/add.cpp:4:1: error:stray’302′ in program
       return x + y;
    ^
    /buildsources/add.cpp:4:1: error:stray’240′ in program
    /buildsources/add.cpp:4:1: error:stray’302′ in program
    /buildsources/add.cpp:4:1: error:stray’240′ in program
    /buildsources/add.cpp:4:1: error:stray’302′ in program
    /buildsources/add.cpp:4:1: error:stray’240′ in program
    /buildsources/add.cpp:4:1: error:stray’302′ in program
    /buildsources/add.cpp:4:1: error:stray’240′ in program
    return code 0

    #include
    #include “add.h”

    int add(int x, int y); // needed so main.cpp knows that add() is a function declared elsewhere

    int main()
    {
    using namespace std;
    cout << "the sum of 3 and 4 is: " << add(x, y) << endl;
    return 0;
    }

    add.cpp

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

    • justin jacobs

      hey alex sorry to message again i retyped the code got same error so i analized it again this time the diagnostic is
      "use of undeclared identifier ‘X’ code is still same a metion befor

    • Alex

      The 240 and 302 refer to unprintable characters that have somehow been inserted into your source code at the start of line 4 of add.cpp.

      Try deleting the “return x + y;” line and retyping it by hand and see if that clears things up.

  • justin jacobs

    this gets error "use of undeclared identifier x"
    then the add.h file gets error macro not used. no errors display for add.cpp

    • Alex

      The problem is this line:

      You’re trying to pass two arguments to function add() named x and y, but you’ve never defined any variables named x and y. You could fix this like this:

      but even better would be like this:

  • Jim

    Hi Alex, lmportant !!
    My C ++ study has been interrupted for a while.  The subject of this lesson is multi-files and I’ve noted that a lot of people here are using a main.cpp files. With their code usually includes the main function.  I would think this is a big mistake for them since the main function is forever changing.  This raises big flag.  Since the main function is different in every program, how should we store and name it.  Certainly not main.cpp every time.

    • Alex

      It’s fine to put your main function in a file called main.cpp. Each new project you create would have its own unique version of main.cpp (in the directory for that project). That way, each project can have a different main.cpp unique to it, and there’s no conflict.

  • I am auditing this course.  I am an old timer, graduated Penn State on a Korean War GI. Bill (B.S. Geophysics).  My only programming experience was an undergraduate course in FORTRAN (Anyone remember that?).  I am using a downloaded version of Visual Studio Community 2015.  I have followed and, I believe understood all lessons up to Lesson 1.8, (Programs with Multiple Files) but now I’m not certain I’m fully on board.  If I am missing the boat, I want to get back on board even if I need to begin, again, from lesson 0.1.
    The text for lesson 1.8 (Under, Adding Files to your project in Visual Studio) states: “right click on “Source Files” in the Solution Explorer window on the left, and choose Add -> New Item.”  Well, I guess I’m really out to lunch because I see nothing on the left of my screen, ZERO (Nothing besides (to the left of) the area where I enter code.)  Nothing labeled “Solution Explorer” can be found anywhere.
    I’ve searched the “comments” and no one seems to have a similar issue.  Besides, most of the comments seem to be coming from persons much more experienced than me.
    I greatly enjoy the course and I believe I’ve learned quite a bit; however, I may have reached my limit of understanding.  I am eager to move on but I feel as if I don’t understand the fundamentals of Visual Studio.
    I’ve searched for tutorials for VS 2015 but those I’ve found explore many applications of the product and are not nearly basis enough.  There seems to be much of VS I need to know and which I missed somewhere along the line.
    AM I BEYOND HOPE?

    • Jim

      Bristol Bob,

      You need to start VS (Visual Studio) in a project environment in order to see the left part of the screen your talking about. Open and save VS using the path to a project give it a name you want like testproj.  Once you have a project setup you will need to copy and paste the main and add files from this lesson.

      • Thank you for the reply but I’m still in the dark.  I believe more than a casual knowledge of programming is needed for this course.  It was my understanding thus would be OK for beginners.
        I have no idea what you mean by "open and save VS using the path to a project."
        I’ll spend another day trying to think this through.  However, I don’t, at his time, believe I’ll be able to finish this course which is very disappointing.

    • Alex

      Looks like maybe your solution explorer window got closed somehow.

      You can resummon it from View menu -> Solution Explorer.

      If you can’t find it there, you probably don’t have a project open. We talk about how to create projects in lesson 0.6. You’ll need a new project for each program you create (or reuse an old one, if you don’t mind overwriting your previous work).

  • I have NOT been giving names to my exercises (projects?).  After reviewing Chapter 0.6, that seems to be a mistake.  As Jim suggested, I need to name anything I work with in the IDE.  Is this correct?  Please excuse my ignorance.  As I said in my original communique, I am an old timer!

    • Alex

      I don’t think Visual Studio will let you create a project without giving it a name (it’ll give you a default name like ConsoleApplication1 if you don’t pick one).

  • Until now, I’ve been using ConoleApplications 1 through 10 for my practice and exercises.  WRONG?  Now, as understand it, EVERY time I use the IDE,I need to declare a New Project and name it.  I haven’t had time to check this out but I’m thinking this will solve my initial problem (the Source Files issue, Chapter 1.8)and explain some behavior I attested to inexperience.

    • Alex

      Using the default names (ConsoleApplication1 through 10) is fine if you don’t want to provide a better name.

      You don’t need to declare a new project every time you use the IDE.

      If you are working on an existing program, you can open an existing project rather than creating a new one.
      If you are starting a new program, you can either create a new project, or you can open an existing one and replace the contents.

  • Jim

    Alex, and Bristol Bob,  I’m using code::blocks but I’d think VS has a file menu or a simple way to start a project.  B. Bob you don’t have to be particular about what you name a project. Use project 1 for example or like Alex says use the ones you used before.  You may have to delete what’s in there.  You are in a beginners section and if you have some minor problems, someone on this site may be able to help you. Make sure you cover exactly what your trying to do.  Make it brief but to the point. Make sure to always include you IDE name.
    Alex is very familiar with Visual Studio but you may have to wait to get your questions answered..
    B Bob It sound to me like you trying to learn both c++ and how to use VS at the same time, that’s pretty hard.  May I suggest that you join the VS Forum you can search their site for help too.  Good Luck I’m a beginner to!

  • Nyap

    tl;dr version of this lesson:
    - multiple .cpp files are used for organisation purposes
    - you use a forward declaration to tell the compiler that this is an identifier which is elsewhere (in this case in a different file)

  • Harshul

    So what is the job of linker if we have to explicitly provide declaration for our functions. According to the concept linker should automatically link all the .cpp files into one which would solve the problem for declarations. But after providing a prototype the linker seems to work properly??

    • Alex

      I’m not sure I understand what you’re asking. The compiler turns individual code files into object files. The linker stitches multiple object files together into an executable, and resolves dependencies between files (e.g. where you call a function from one file, but that function is defined in another file).

  • Harshul

    Ok let me put it in a much simpler way to you:-

    Let us say there are 2 files start which contains the main() and second one contains the function definition of add(). So If I compile my project then compiler will turn individual files into object files and then linker would stitch them to a single file. But in that single file ( which is written in some basic machine language ) the definition of add() is present within that file along with main() which is using add() so why our compiler shows up error.

    But when we place a signature for our add() then it seems to work perfectly.

    If it was not working properly in the first case then how is it working in second one

    • Alex

      Remember that the compiler compiles things before the linker ever runs. And the compiler compiles file by file. So when the compiler finds a call to add() in your main code file, it goes, “I haven’t seen a declaration for that” and throws an error. End of story. The linker never even comes into the picture.

      When you add a forward declaration for add(), then the compiler is satisfied that add() exists somewhere, even if it doesn’t know where. It relies on the linker to figure out where. And the linker either will (it’s in the second file), or else the linker will throw an error that it couldn’t find a definition for add().

  • Harshul

    Ok, so according to you linker deals with errors of definition which points to the existence of a second compiler that works after linker and checks for errors??

    But while working with a single file if one does not write the definition then compiler shows up error it does not waits for linker it simply reports error?

    What is linker’s job, it breaks code into many object file and links them as needed. So is there any specific order of how the files are linked (i.e. which file appears first and which last)?

    • Alex

      Second compiler? No. The compiler goes through each file in turn and looks for declaration errors. Once all files are compiled, then the linker runs and links them all together.

      If you try to make a function call without declaring the function, the compile will flag that as an error as using an undeclared identifier is a compile error. However, consider what happens if we add a forward declaration:

      In this case, the compiler will see the call to add(), and go, “oh, this was forward declared, add() must live in another file”, and give you a pass. Then you’ll get a linker error, because the linker can’t find a definition for function add().

      The compiler turns code files into objects, the linker turns objects into executables (or libraries). The linker links files in the order that the object file filenames are provided. When you’re using an IDE, that ordering is up to your IDE.

  • Harshul

    As you said that linker would check for definition of add in other files. But linker’s job is to link all the object files not to check whether something exists in another file. The duty of checking if the code properly works is of compiler but compiler did not check for any definition.

    • Alex

      Your statement about the compiler and linker are both incorrect.

      The job of the compiler is not to ensure your code properly works -- that’s _your_ job. The compiler ensures the code is syntactically correct. Part of this is ensuring you’ve provided declarations for all the identifiers you’ve used. Note that a forward declaration satisfies this.

      The job of the linker is to combine all your object files into an executable, and resolve all identifiers to memory addresses. Therefore, if you’ve used an identifier and provided a declaration (to satisfy the compiler), but never actually defined the identifier, when the linker combines all of the object files, it will discover that your identifier was never defined. So yes, it is the linker’s job to determine whether something exists in another file.

      • Harshul

        Wait….Functions are using call and return methodology so how can we resolve them to their addresses?? We can resolve them to their addresses by using the keyword inline only.

        • Alex

          I think you misunderstand what I mean by “resolve”. When we write C++ code, we use identifiers to name things -- variables and functions for example. This is for our convenience. However, the CPU doesn’t care about names, it only cares about memory addresses. So when you link your program, the linker translates all your names into the appropriate memory addresses.

          • Harshul

            Ok so compiler checks if all the identifiers are defined or not. But the linker handles the job of making program usable (so that computer can use identifiers ) them by replacing identifiers to the respective addresses (which computer can understand).

            • Alex

              Almost right. The compiler has different rules about whether things need to be defined or just declared. In many cases, a declaration will satisfy the compiler. This is why you can use a function forward declaration to satisfy the compiler.

  • Eva Ho

    Hi!!!
    This is the most organized and well-explained tutorial ever!
    English is my second language, so it is hard for me to find a suitable tutorial for me.
    Thank you so much for this wonderful tutorial.

    I use Xcode 7.3.1 to practice multiple-file program, and the outcome is very strange.

    What is the problem?

    [

    #include <iostream>

    int add(int a, int b);

    int main()
    {
        std::cout<<add(1,2);
        return 0;
    }

    /code]

    The output is [llbd]

    • Alex

      I’ve never used XCode, so I don’t know why it’s printing [llbd]. Sorry. 🙁

      This program shouldn’t even link, since there is no definition for function add().

    • Eva Ho

      Thank you for getting back to me!
      No problem, I will find the answer somewhere! 😀

      I defined add() in another file, and used forward declaration.
      Sorry, I should have added comment at the end of the statement.

  • Eliezer Bruin Braganza

    Dear Alex, In this tutorial i did as you instructed, however i am getting an error message "undefined reference to ‘WinMain@16’. I am using code::blocks 16.01. I have made two files one main.cpp and the other add.cpp and have copy paste the code from the site, still i am getting the above mentioned error. Both the .cpp files are in the same project and also the compile and link have been checked.

    • Alex

      Did you make sure to create a console application and not a windows application?

      If so, then maybe try some of the ideas here, or do a search of that error message on Google.

  • Hey Alex do we need a .cpp file in order to create a header file or can it be done directly.
    Thanks you for u tutorial very easy to understand C#.

    • Alex

      You can directly create header files, and it’s fine to have a header file without a corresponding .cpp file (or vice-versa -- they don’t always have to travel as a pair, though they often do).

  • Murlidhar

    Hi, Alex cant understand properly how to add add.cpp to main.cpp can u please give me step by step instruction. From making main.cpp and add.cpp to adding them together please.

  • Suraj

    How can this be done in turbo C++.Merging of multiple files?

  • maria

    my compiler shows  error…i dont know why??

    [/code]
    #include <iostream>

    int add (int x,int y);

    using namespace std;

    int main()
    {
        cout << " 3+4 is " << add(3,4)<<endl ;
        return 0;
    }

    #include <iostream>

    int add (int x ,int y)
    {

        return x+y;
    }

    • Alex

      I don’t know why either, this compiles and runs fine for me. What error are you getting?

      If your add function is in a different file, I suspect maybe that file isn’t getting compiled. Make sure it’s added into your project.

  • maria

    ||=== Build: Debug in addtwonums2 (compiler: GNU GCC Compiler) ===|
    C:\Program Files\CodeBlocks\MinGW\bin\..\lib\gcc\mingw32\4.9.2\..\..\..\libmingw32.a(main.o):main.c:(.text.startup+0xa7)||undefined reference to `WinMain@16’|
    ||error: ld returned 1 exit status|
    ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

    it shows this error

  • maria

    i fixed the problem but it shows another problem when it compiles……it prints Hello World:(:(
    and both of these file are saved in the same folder….

    [code]
    filename: add.cpp

    #include <iostream>

    using namespace std;

    int add(int x, int y)
    {

      return x+y;
    }
    filename: main.cpp

    #include <iostream>

    using namespace std;

    int main()
    {
        cout << "Hello world!" << endl;
        return 0;
    }

  • maria

    i want to add two numbers using seperate files….

    add.cpp
    #include <iostream>

    using namespace std;

    int add(int x, int y)
    {

      return x+y;
    }

    main.cpp

    #include <iostream>

    int add (int x, int y);

    int main()
    {
        std::cout << "sum of 3 and 4 is " << add(3,4)<< std::endl;
        return 0;
    }

    my compiler shows this error……….how to resolve this problem

    ||=== Build file: "no target" in "no project" (compiler: unknown) ===|
    C:\Users\maria\Desktop\c++\addtwonums\main.o:main.cpp|| undefined reference to `add(int, int)’|
    ||error: ld returned 1 exit status|
    ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

    • Alex

      I don’t see anything wrong here. Is add.cpp being compiled and linked?

      • Maria

        Sorry I didn’t get your point

        • Alex

          It looks like your linker might be failing to link add.cpp into your program, so when it goes to connect the call to add() from main.cpp, it can’t find a definition for function add(). The most likely cause for this is that you are compiling main.cpp but not add.cpp (e.g. you created add.cpp but forgot to add it to your project, so the compiler doesn’t know you want it compiled). When you compile your program, you should see it compile two files: main.cpp and add.cpp. Is this happening?

  • Hello! First and foremost I want to thank you for creating such a comprehensive list of c++ basics they’ve been incredibly helpful for me as a ComSci undergrad. I usually just Google problems when I encounter them but as I was reading these pages to review I got to the part about multi-file projects. My first program I’ve made is a console based calculator, and I’ve recently split its functionality into different classes. Now, for me personally, I want the main function to be the only function in the main.cpp file, so I created a Menu class that handles all the menu text outputs as well as all the option choosing functionality. The other class is a Math class that handles the different "modes" of the calculator, as well as asking for values, calculating, and returning results. So my project consists of 5 files:
    main.cpp, Math.cpp, Math.h, Menu.cpp, and Menu.h. My header files contain all the forward declarations and the .cpp files of the classes contain all the actual function implementation.

    You mentioned that you could use a forward declaration at the beginning of the main.cpp to ensure that you could run its functions in main(). FOR ME, it looks like this:

    You mentioned that it’s not good to do the #include for the forward declarations because it can get problematic as the program gets larger. But when I try to comment out the includes like so:

    The error I get is "use of undeclared identifier" for the function. If I include the headers and use the "Menu m;" object thing everything works fine. So my question is… is my program okay the way it is because I’m using classes? Or is there potential for bad habits if I continue the way I am? Thanks for you time!

    Also don’t know if it makes a difference but I’m using Xcode.

    • Alex

      > You mentioned that it’s not good to do the #include for the forward declarations because it can get problematic as the program gets larger

      It sounds like you got what I was saying backwards -- manually typing in forward declarations at the top of your code files is not maintainable. Creating and including header files is better. So you should be using header files. Is there something I said somewhere that confused you?

      Otherwise it seems like your program is just fine.

  • My dear Teacher,
    Please let me say that in program "main.cpp with forward declaration" there is obvious error in the body of "main". Correct is:
    std::cout << "The sum of 3 and 4 is: " << add(3, 4) << std::endl;
    With regards and friendship.

    • Alex

      Thanks for pointing that out. I updated a bunch of lessons the other night to make them more compliant with best practices and was going cross-eyed from all the cut and paste.

  • maria

    thanks alex …it worked

  • Mark

    This is odd … my files seems to be linked properly since I’m not getting any errors and the command line popping up but not getting the result 7. Getting just empty line with "Press any key to continue".

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter