Search

1.8 — Programs with multiple files

As programs get larger, it is not uncommon to split them into multiple files for organizational or reusability purposes. One advantage of working with an IDE is they make working with multiple files much easier. You already know how to create and compile single-file projects. Adding new files to existing projects is very easy.

Adding files to your project in Visual Studio

In Visual Studio, right click on “Source Files” in the Solution Explorer window on the left, and choose Add -> New Item. Make sure you have “C++ File (.cpp)” selected. Give the new file a name, and it will be added to your project.

Note: If you create a new file from the File menu instead of from your project in the Solution Explorer, the new file won’t be added to your project automatically. You’ll have to add it to the project manually. To do so, right click on “Source Files” in the Solution Explorer, choose Add -> Existing Item, and then select your file.

When you compile your program, the new file will be automatically included, since it’s part of your project.

Adding files to your project in Code::Blocks

In Code::Blocks, go to the file menu and choose “new file”. Give the new file a name (don’t forget the .cpp extension), and Code::Blocks will ask you if you want to add it to the active project. Click “Yes”. Note that you will also have to click the “Release” and “Debug” checkboxes, to make sure it gets added to both versions.

If Code::Blocks doesn’t ask you whether you want to add the file to the active project, or if the file doesn’t show up in the project pane, you’ll need to add it to the project manually. To do so, right click on the project name in the project pane, choose “Add File”, locate the file you just created, and add it to the project.

Now when you compile your program, the new file will be automatically included, since it’s part of your project.

If the new file isn’t compiling or linking with Code::Blocks, make sure the file is set to compile and link. To do so, right click on the file in the project pane, and choose “Properties”. Under the “General” tab, you should see checkboxes that control whether the file is compiled and linked. Make sure they are checked.

Adding files to your project from the command line

From the command line, you can create the additional file yourself, using your favorite editor, and give it a name. When you compile your program, you’ll need to include all of the relevant code files on the compile line. For example: “g++ main.cpp add.cpp -o main”, where main.cpp and add.cpp are the names of your code files, and main is the name of the output file.

A multi-file example

Now, consider the following multiple-file program:

add.cpp:

main.cpp:

Try compiling this program for yourself. You will note that it doesn’t compile, and it gives the same compiler error as the program in the previous lesson where the functions were declared in the wrong order:

main.cpp(6) : error C3861: 'add': identifier not found

When the compiler is compiling a code file, it does not know about anything in other code files, or remember anything it has seen from previously compiled code files. In this case, when compiling main.cpp, it doesn’t remember that it previously compiled function add() in add.cpp, so it complains that doesn’t know what identifier add is.

This limited visibility and lack of memory is intentional, so that files may have functions or variables that have the same names as those in other files without causing a naming conflict. We’ll see an example of this in the next lesson.

However, in this case, we want main.cpp to know about (and use) the add() function that lives in add.cpp. To give main.cpp access to the add function, we can use a forward declaration:

main.cpp with forward declaration:

Now, when the compiler is compiling main.cpp, it will know what add() is. Using this method, we can give files access to functions that live in another file.

Try compiling add.cpp and the main.cpp with the forward declaration for yourself. If you get a linker error, make sure you’ve added add.cpp to your project or compilation line properly.

Something went wrong!

There are plenty of things that can go wrong the first time you try to work with multiple files. If you tried the above example and ran into an error, check the following:

1. If you get a compiler error about add() not being defined in main(), you probably forgot the forward declaration in main.

2. If you get a linker error about add not being defined, e.g.

unresolved external symbol "int __cdecl add(int,int)" (?add@@YAHHH@Z) referenced in function _main

2a. …the most likely reason is that add.cpp is not added to your project correctly. If you’re using Visual Studio or Code::Blocks, you should see add.cpp listed in the Solution Explorer/project pane on the left side of the IDE. If you don’t, right click on your project, and add the file, then try compiling again. If you’re compiling on the command line, don’t forget to include both main.cpp and add.cpp in your compile command.

2b. …it’s possible that you added add.cpp to the wrong project.

2c. …it’s possible that the file is set to not compile or link. Check the file properties and ensure the file is configured to be compiled/linked. In Code::Blocks, compile and link are separate checkboxes that should be checked. In Visual Studio, there’s an “exclude from build” option that should be set to “no” or left blank.

3. If you’re using Visual Studio with precompiled headers, every code file needs to #include “stdafx.h”. This includes both main.cpp and add.cpp.

4. Do not #include “add.cpp” from main.cpp. This will cause the compiler to insert the contents of add.cpp directly into main.cpp instead of treating them as separate files. While it may compile and run for this simple example, you will encounter problems down the road using this method.

Conclusion

When the compiler compiles a multi-file program, it may compile the files in any order. Additionally, it compiles each file individually, with no knowledge of what is in other files.

We will begin working with multiple files a lot once we get into object-oriented programming, so now’s as good a time as any to make sure you understand how to add and compile multiple file projects.

Reminder: Whenever you create a new code (.cpp) file, you will need to add it to your project so that it gets compiled.

1.8a -- Naming conflicts and the std namespace
Index
1.7 -- Forward declarations and definitions

282 comments to 1.8 — Programs with multiple files

  • Ian Luria

    Alex,

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

  • 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

    THE BUILD LOG SAYS THE FOLLOWING

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

    THE TWO FILES HAS BUILD OK BUT WHILE RUNNING THIS POPS OUT. PLEASE HELP THIS OUT!!!

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

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

          okay,
          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.
    file1.cpp

    file2.cpp

  • 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
    https://www.tutorialspoint.com/compile_cpp_online.php
    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.
    iLikeDogs.cpp

    cats.cpp

    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
      https://www.tutorialspoint.com/compile_cpp_online.php
      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
          https://www.tutorialspoint.com/compile_cpp_online.php
          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….

    add.cpp
    #include <iostream>

    using namespace std;

    int add(int x, int y)
    {

      return x+y;
    }

    main.cpp

    #include <iostream>

    int add (int x, int y);

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

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

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

    • Alex

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

      • Maria

        Sorry I didn’t get your point

        • Alex

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

  • maria

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

    [code]
    filename: add.cpp

    #include <iostream>

    using namespace std;

    int add(int x, int y)
    {

      return x+y;
    }
    filename: main.cpp

    #include <iostream>

    using namespace std;

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

  • maria

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

    • Alex

      Sounds like maybe you built the wrong kind of project. Did you create a console project?

    • Ameen

      i was getting the same error….what i did is that i changed the extension of my add function to the same as my main function i.e .cpp . but while doing so my previous file got overwrite.So Alex is there anyway such that when i add a new file both file has the same type? BTW the program worked.

      Thankyou

  • maria

    my compiler shows  error…i dont know why??

    [/code]
    #include <iostream>

    int add (int x,int y);

    using namespace std;

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

    #include <iostream>

    int add (int x ,int y)
    {

        return x+y;
    }

    • Alex

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

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

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

Leave a Comment

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