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:



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


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

262 comments to 1.8 — Programs with multiple files

  • Ian Luria


    This sentence is causing me a lot of confusion: "In this case, when compiling add.cpp, it doesn’t remember that it previously compiled function add() in main.cpp, so it complains that doesn’t know what add is."  

    Why would add.cpp complain that it doesn’t know what the function add() is when add() is actually being defined in add.cpp?  In other words, why would add.cpp be looking to main.cpp for the definition of the function add() when the purpose of add.cpp is to define add()?  

    It seems like you have that sentence backwards:  When compiling main.cpp, it doesn’t remember that it previously complied function add() in add.cpp.

    Please clarify for me!  Thank you.

  • Dom

    I have come back to this chapter after finishing Chapter 6.x and tried to separate the functions involved with the simplified Blackjack game into their own file. It worked fine, however there’s a slightly confusing issue that’s cropped up.
    I put the function

    into its own file and it wouldn’t compile without

    at the top of the new file. But now I can comment the include out in both the main .cpp and the new one and the program still builds and runs completely fine. Do you have any idea why this is possible?

    • Alex

      It’s possible another included header, or the compiler itself, is including cstdlib. You should still include it explicitly.

      • Dom

        Thanks for the reply. Yeah, it turns out that there are a chain of headers including headers starting with iostream.
        The chain is: iostream -> istream -> ostream -> ios -> xlocnum -> cstdlib, which is included among other headers and includes multiple other headers itself, leading into more chains.

        I appreciate header guards a bit more now.

  • Aakash

    I inlcuded multiple files in my code blocks IDE. It gives me an error that main function is already declared as there is already  a file named main.cpp with a simple "hello world" program in it.
    If I now add files to this , I get error that main is defined before. How do i get rid of this? please help.

  • M

    I’m confused about the first example not compiling. The error for the example says that add.cpp won’t compile because the function add(int x, int y) isn’t defined, but wouldn’t it be main.cpp that doesn’t compile because add isn’t defined in main.cpp? I tried the example in Visual Studio 2017, and the compiler gave me an error on main.cpp.

  • Ashish


    --------- Run: Debug in helloworld (compiler: GNU GCC Compiler)----------

    Checking for existence: C:CBProjectshelloworldbinDebughelloworld.exe
    Executing: "C:CodeBlocks/cb_console_runner.exe" "C:CBProjectshelloworldbinDebughelloworld.exe"  (in C:CBProjectshelloworld.)
    Process terminated with status 4256912 (0 minute(s), 10 second(s))


  • mina

    Hello dear teacher
    When I have new item cpp and it runs correctly,now I want to add another new item,but it has error and not run.
    What is the problem??

  • My dear c++ Teacher,
    Please let me ask you whether following way is correct. In visual studio 2017.
    1. I did click on File > New > Project.
    2. In appeared window I given project’s name "main".
    3. On the editor area I copied and pasted your file main.cpp with forward declaration. I saved main.cpp
    4. In "Solution Explorer" I did right click on Source Files > Add > New item.
    5. On new window I did click on C++ File (.cpp) and then on Add.
    6. On new editor’s area copied and pasted your add.cpp file. I saved add.cpp.
    7. I compiled and executed project fine.
    I have one question. Is it right that main.cpp is both project and file?
    With regards and friendship.

    • Alex

      The project is just main, whereas the code file is main.cpp. That’s totally fine.

      • My dear c++ Teacher,
        Please accept my many thanks for you replied  my message and for your helpful answer.
        Also please let me one more question:
        Is it true that project’s name must be name of a code file?
        With regards and friendship.

        • Alex

          No, the project name can be whatever you like (subject to OS constraints). Your code files can also have any name you like (also subject to OS constraints). The only naming requirement is that one of the code files in the project must have a function named main.

  • sam

    hi there!
    I am facing a problem on this topic:
    you see i created a file named "bob.cpp" to try something out, after i was done i removed the file from my project(from the file menu >> move bob.cpp to >> miscellaneous files)   and deleted it from my solution explorer, but i kept having errors saying that file "bob.cpp" isn’t found…
    so i made another file named it "bob.cpp" (thinking i would trick the compiler into thinking that new file is the same one its asking for ) but the compiler isn’t as dumb as i hoped and now its asking for 2 "bob.cpp" files…………
    the errors now I’m facing are:

    Severity Code Description Project File Suppression State line

    Error C1083 Cannot open source file: ‘..bob.cpp’: No such file or directory learning2 C:Users-Desktoplearning2learning2c1xx 1

    Error C1083 Cannot open source file: ‘bob.cpp’: No such file or directory learning2 C:Users-Desktoplearning2learning2c1xx 1

    in fact this is the second time i face this problem but the first time i faced i simply deleted the project and started another one. i can do the same now and I’ll probably do it, but i want to know a solution to this problem fearing that i would face it in the future after coding a big/hard program.

    ps: I’m using visual studio 2017

  • sam

    hi, I’m using Visual studio 2017 here.
    i tried to compile but i always get errors:
    file name "learning2.cpp":

    file name "add.cpp":

    and the errors I’m getting are:
    Severity    Code    Description    Project    File    Line    Suppression State
    Error    LNK1120    1 unresolved externals    learning2    C:Users---Desktoplearning2Debuglearning2.exe    1    
    Error    LNK2019    unresolved external symbol "int __cdecl add(int,int)" (?add@@YAHHH@Z) referenced in function _main    learning2    C:Users--Desktoplearning2learning2learning2.obj    1    
    Error    LNK1120    1 unresolved externals     C:Users--Desktoplearning2learning2learning2.vcxproj    C:Users--Desktoplearning2x64Debuglearning2.exe    1    
    Error    LNK2019    unresolved external symbol "int __cdecl add(int,int)" (?add@@YAHHH@Z) referenced in function main     C:Users--Desktoplearning2learning2learning2.vcxproj    C:Users--Desktoplearning2learning2learning2.obj    1    

    i have no idea what these errors mean, and I’m not sure if there is a mistake in my code.
    i looked into your tips and im sure that i have "add.cpp" in my project folder (project name is "learning2").
    my best guess is that the file "add.cpp" is "excluded from build" i am looking around to find this option and set it on "no" or blank as you suggested but i don’t know where it is and i cant find it.

    • Alex

      It certainly sounds like add.cpp isn’t getting compiled. When you compile your program, you should see it compile both learning2.cpp and add.cpp.

      When you say “project folder”, do you mean on disk? Or do you mean in the solution pane? You should see both learning2.cpp and add.cpp in your solution explorer under the source files directory. If add.cpp isn’t there, add it.

      • sam

        yeah i can see both "add.cpp" and "learning2.cpp" in my solution explorer.
        however, i set my solution explorer to "folder view" to see these…
        i do that by clicking on "solutions and folders". there is a small arrow next to the button.

        when i click it, it shows me 2 options
        - "learning2 (C:/users/-/desktop/learning2)"
        - "learning2.sln"

        when i click
        "learning2 (C:/users/-/desktop/learning2)"

        i can see the files and their location including "add.cpp" and "learning2.cpp" they are next to each other in the "x64" folder inside my project.

        on the other hand when i click

        i get nothing on my solution explorer…

        and yes you are right i tried to compile my program again and it showed me that the compiler was working "learning2.cpp" and it didn’t mention "add.cpp".

        i deleted and recreated "add.cpp" to make sure. i added it by
        right clicking on my "solution explorer" window
        >> add >> add new item >> visual C++ >> C++ file (.cpp).

        and again the same file is recreated in the same location in my project folder… and still not compiling.

        • Alex

          You’re clearly adding the add.cpp file to your disk folder, but not to the project itself. I suggest turning off “show all files”, and then right click on the “Source Files” folder in the solution explorer, then choose add->existing item. Then select add.cpp. That should add it to your project.

          • sam

            oh wow, that’s weird!
            i didn’t see your replay until today!
            and i checked back to this page a lot in the past couple of days :/
            if feels great that you read my comment and replayed in that same day! thanks a lot!

            i had to work around the adding files thing because i tried adding it by right-clicking on my project file "learning2" , as i said before. but it didn’t work for me the file "add.cpp" was still not included for compiling in my project.
            i really want to learn the right/fastest/easiest way to do it, but i cant find this "source files" folder in my project folder not on solution explorer nor on disk…

            but again it is working for me so far, which is nice.

            anyhow i faced another problem and i stated it on a comment here, its about deleted files this time ":D .
            i would love to get any advice on how to work it out.

            my way to "work around it" is by making a new project and copy paste everything!
            i don’t think that’s pretty efficient tho. 🙂
            thanks again for the amazing support!

      • sam

        I just realized another thing…
        There is a tab on underneath the file name in the window that i can code in.
        This tab shows the project that the file belongs to.
        I have my main file "learning2.cpp" in the project "learning2"
        While the other file "add.cpp" isn’t in any project and it says "Miscellaneous File"

        I think i just pin pointed my problem here; my file isn’t included in my project.

        So… how can i include it in my project "learning2"? again I’m using "Visual Studio 2017".

        i tried to follow your tip "2a. ..right click on your project, and add the file, then try compiling again.." where should i right click? do you mean in my solution explorer? because i tired that. it opens the "create new file" window the same one when i right-click >> add >> add new item anywhere on my solution explorer, and it creates the same file in the same condition (not included in the project).

        • sam

          HOLY SHIT I FIXED IT!!!!!!!!!!!

          anyone how is having this problem this solution is quite simple.

          1- you need to select the file you want to add to your project -in my case its "add.cpp".
          2- click on the file tab on the top-left.
          3- select [move "filename" to] -in my case its [move add.cpp to]-.
          4- select your project -in my case i have to click on "learning2"-.
          5- congratulations! you did it!

          i hope these 5 simple steps would save some real struggle for others because it took me more than 6 hours of searching over 2 days!

          i feel stupid now because it took me 2 days to find it out…
          but hey, i found it!

          cheers to all! now i can hop to the next lesson.

          and Alex thanks for the amazing lessons, i think you should add these 5 steps ( in your own words of course. as you can tell, my English isn’t the greatest).
          it’s quite unfortunate most tutorials and guides on the internet these days cover things on visual studio 2015-, there isn’t much help when it comes to the 2017 version.

          • Alex

            I’m glad you were able to figure it out. It sounds like you’re doing some sort of workaround to get things working, not taking the shortest path -- but if it’s working for you, run with it.

  • My dear c++ Teacher,
    Please let me, for you are so good, send you one more example of program with multiple (just 2) files.
    With regards and frinedship.


  • Alice

    Took me time to understand what Declare forward is. I’ll explain for slow people like me who willing to read this.

    Notice the last sample he used, add(); doesn’t have a return value/operation, it’s literally “declares” telling main that a function named add() exists somewhere.
    In our case, an add()(a function- no semicolon) with return exists is in another file in the same project(Source files folder).

    add() can be under main() too.
    Why is it suggested to use declaration?
    1- It’s highly recommended to keep main() always on top. Declaring(telling main about a function existing somewhere) is much easier than writing the whole function above main.
    2- main won’t identify a function unless it’s either declared or written above main.
    3- Having the function in another file is the same as writing it under main(), this will help making main.cpp file as short as possible, not to mention the functions will be much easier to find and edit.

    • Alex

      It’s not necessary to keep main() on top -- in fact, it’s often on the bottom of the file in order to avoid having to forward declare other functions in the same file.

      In general, declarations mostly aren’t used this way -- they’re primarily used in header files, and header files are used everywhere. We talk about header files shortly.

  • My dear c++ Teacher,
    Please let me following question to be sure. In your example program I deleted #include <iostream> from main.cpp file and added in add.cpp. Both compilers
    Dev-C++ 5.11   and web based
    complain. Then is it right that #include <iostream> and every #include must be written in the file where function main() is?
    With regards and friendship.

    • Alex

      #include <iostream> tells the compiler what std::cout, std::cin, and std::endl (and some other things) are. Therefore, if you use any of those in a .cpp file, you should include iostream before using them. If your .cpp file does not use any of those things, then including iostream is not required.

      Note that this has nothing to do with where main() is.

      • My dear c++ Teacher,
        Please accept my many thanks for you replied and for your interesting information. I applied it as follows:
        file main.cpp

        file add.cpp

        Output is: The sum of 3 and 4 is: 7
        With regards and friendship.

  • Justin

    Hi, I recently started trying to learn some programming and am using visual studios. I seem to be a little stuck on this and can’t figure it out. I can run the program and it works but if I try build solution I keep geeting an error.


    I keep getting this error;

    1>MSVCRTD.lib(exe_main.obj) : error LNK2019: unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
    1>c:\VC2005Projects\iLikeDogs\Debug\cats.exe : fatal error LNK1120: 1 unresolved externals

    any help would be appreciated.

    • My dear c++ Teacher,
      Please let me help Mr. Justin.
      Mr. Justin you must rename iLikeDogs.cpp to main.cpp. It works fine by web based compiler
      With regards and friendship.

      • Justin

        How do I rename it? I tried renaming the project but it didn’t seem to change anything inside. From inside the project I tried changing the name in the containing folder but that made it so it could not find the program to run at all and stopped working.

        I feel a little silly for asking a question like how to rename it but it seems a little more complicated than normal, right clicking on the name does not bring up the option to rename it.

        Thank you for the response Georges, any further assistance would be appreciated.

        • My dear c++ Teacher,
          Please let me answer for second time Mr. Justin.
          Mr. Justin, our dear Teacher, is right.
          Your project with file names you given, runs fine by compiler

          I apologize for my mistake.
          With regards and friendship.

      • Alex

        Just to be clear, the file containing the main function does not need to be named main.cpp. It can be named anything you want. Most often, it is named main.cpp, or whatever your application name is.

    • Alex

      My best guess is that iLikeDogs.cpp is not being compiled because you haven’t added it to your project. Add it to your project and try recompiling.

  • Nishant

    Alex I get an error showing Id return 1 exit status ,what should i do.

  • Wyatt

    Hi. I’m trying to use two files together. Both are simple "Hello world"-like programs. Both run fine independently, and when I attach my Hello World to the other file, I can check on it in a tab next to the Solution Explorer tab. Everything seems to go fine, except when I look at the file I attached, there’s nothing in it. It’s totally blank. That’s not supposed to happen, right? I opened that file in its independent, unattached form, and it was just as it should be, so why is it blank when I attach it to another?

    • Alex

      I’m not sure what you mean by “attached” in this context.

      • My dear c++ Teacher,
        Please let me say my view. Mr. Wyatt probably makes same mistake as Mr. Justin above. He does not give name main.cpp to any file.
        With regards and friendship.

      • Wyatt

        Added to my project. I believe I did all the steps correctly, but the added file is blank. Did something go wrong, or is it supposed to be empty? I’m using Visual Studio 2015, if that helps.

        • Alex

          If you’re adding a new file, it should be blank. If you’re adding an existing file, it should contain whatever was in that file.

          • Wyatt2

            Hi, this is Wyatt’s brother. We’re studying C++ together. For clarification, I’m the guy that was confused about return values back in lesson 1.4 in January. My alias was Wyatt then too. 🙂 Anyway, we somewhat figured out the issue. Here’s what happened:

            He tried to add a file already existed, but he clicked "New Item" & created a new file with the same name as the old one he wanted to add. Thus, it appeared to him that it was the old file, but blank, when in reality, it was a new file, & that’s why it was blank.

            So that’s solved. But then I tried to add the old one & see if we could get that to work, & couldn’t figure out what to do because there were multiple files with the same name & yadda yadda & it got messy, so eventually we just deleted all files with that name in the File Explorer & got an error message but it seemed like it worked anyway, I don’t know…

            Either way, we understand what caused the issue now & the computer isn’t on fire, so I think we’re pretty much good. Thanks.

  • C++ Student

    My problem is that my compiler doesn’t contain projects. It does allow me to create folders and files…if I have multiple files in the same folder, will it work the same as multiple files in a project? I’m using Mobile C.

  • AmirR

    By far the best site to learn C++. So far, so great, everything is easily understandable. I can’t believe you’re maintaing it for 10 years. It only needs "return to top" in bottom, comments are endless 😛

  • Mustafa

    But how does the compiler know which file to read first?

    • Alex

      It’s up to your IDE to determine the compile order. Or, if you’re using the command line, the compiler will generally compiler files in the order you specify.

      However, in most cases, it really doesn’t matter what order your files are compiled in. Each file should be self-sufficient, and your program should be compilable in any order.

  • Matt

    I’m using Xcode since it was recommended for Mac users in the introduction.  How I wish you could have included Xcode instructions.  I think I’ve sort of figured it out, but I’m not sure.   I created a new .cpp file, and at the same time it created an .hpp with the same name.  Did I do it right?  What’s the .hpp file for?  Can someone get me on the right track here using Xcode?

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

  • maria

    thanks alex …it worked

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

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

  • maria

    i want to add two numbers using seperate files….

    #include <iostream>

    using namespace std;

    int add(int x, int y)

      return x+y;


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

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

    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

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

    my compiler shows  error…i dont know why??

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

  • Suraj

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

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

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

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

  • Eva Ho

    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()
        return 0;


    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.

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

  • 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

    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

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

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

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

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

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

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

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

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

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

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


    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.

  • 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

  • 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

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



    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.

  • Thomas Keith


    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.


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

  • Thomas Keith

    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

    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


    • 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


    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;
        std::cin >> x;
        int y = 0;
        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?


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


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

      Do the same for variable y.

  • 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

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

  • Joseph

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



    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:

  • Jim

    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.

  • 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

    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.

  • 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

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

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

  • Thank you for an excellent tutorial, Alex.

    Your hard work and commitment is greatly appreciated!

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

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

  • Juan Diego

    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.

  • Amin

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

  • amin

    how different are the other languages?
    thank you

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

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

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


    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.

  • newuserba

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

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

    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

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

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


    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.

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

  • jvanosda

    For those having problems, I did the following:

    #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;

    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.

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

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

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

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

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

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

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

    //First attempt at a project with function defined separately
    using namespace std;

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

    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;

    using namespace std;

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


  • 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

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

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

  • Cleverlegs



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

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

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

  • 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

  • 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

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

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

  • Adele


    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


    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.


    • 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


    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!


  • 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\ [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 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:


    here is the code in 2nd file


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


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


  • 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


  • 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

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