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

  • 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

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

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

    What is the problem?

    [

    #include <iostream>

    int add(int a, int b);

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

    /code]

    The output is [llbd]

    • Alex

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

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

    • Eva Ho

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

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

  • 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.
    AM I BEYOND HOPE?

    • Jim

      Bristol Bob,

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

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

    • Alex

      Looks like maybe your solution explorer window got closed somehow.

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

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

  • 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
    #include “add.h”

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

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

    add.cpp

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

    • justin jacobs

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

    • Alex

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

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

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

    main.cpp

    io.cpp

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

    • Alex

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

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

  • Thomas Keith

    Alex,

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

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

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

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

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

    precisely because

    was unsuccessful.

    Thanks!

    • Alex

      Thanks for explaining your thinking.

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

      So, when we do this:

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

      However, when we do this:

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

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

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

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

  • Thomas Keith

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

    • Alex

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

  • Thomas Keith

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

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

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

    Thanks

    • Alex

      All of the above should work.

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

  • Thomas Keith

    Alex,

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

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

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

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

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

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

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

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

        return 0;
    }

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

    Thanks

    • Alex

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

      The answer is simple. Replace:

      with:

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

      Do the same for variable y.

  • Freffy

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

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

    • Alex

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

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

      • Freffy

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

  • Joseph

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

    multiply.cpp

    main.cpp

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

    and I am baffled…lol

    • Alex

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

      It should be:

  • Jim

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

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

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

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

    • Alex

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

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

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

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

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

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

  • Jim

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

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

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

    I hope this helps other users.

  • Jim

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

Leave a Comment

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