How to Write Multi Files Program in C++

Discussion in 'C++' started by usmanmalik, Jan 22, 2014.

  1. usmanmalik

    usmanmalik New Member

    Joined:
    Dec 28, 2013
    Messages:
    19
    Likes Received:
    14
    Trophy Points:
    0
    In my previous articles, I had introduces you to some of the fundamental concepts of the C++ language. However, you would have noticed that all the code we wrote, resided in a single file. We developed object oriented programs where we used multiple classes, but all those classes were in a single file. We also declared functions outside the main function but they were also in the same file. This single file approach is good for understanding the basic programming concepts at colleges of universities. However, industries don’t work that way. Once you enter IT industry or some software house, you will come across situations where you will have to organize your code into more structured form which is easier to manage and maintain. In such scenarios, code of a program is further divided into multiple files. Such programs are called, multi-file programs.

    Multi-file programs are those programs where code is distributed into multiple files communicating with each other. This is a more practical and realistic approach towards advanced programming where we want loosely coupled code module that can communicate with each other. A question here arises that why should we prefer multi-file programs. Advantages of using multiple files for a program are numerous. For instance, if you write code for a class in a separate document, you can use that class in multiple programs. It increases reusability of the code. Furthermore, if you want to change anything in a class, you will only have to change it in that particularly document and the change will be automatically reflected in all the documents referring to this document. Furthermore, it is advisable to write large complex programs in multiple files. And last but not the least, in large organizations; several programmers are working on a project. In such scenarios, each programmer is responsible for designing designated modules; therefore separate documents for each programmer, are convenient to code and then subsequently integrate.

    In this article, I have explained the basics of using multiple files in a program. If you are using an IDE such as Eclipse, Visual Studio, NetBeans etc., multi-file programming becomes lot more easier. For the purpose of this article, we will be using Visual studio 2010. We will demonstrate with the help of example, how can you can structure your code into multiple files and how can you refer to the code in other documents.

    Before dwelling into the details of how we can actually write a code into multiple files, there are few concepts that need to be explained. After you understand these concepts, it will be much easier for you to understand the structure of multiple file programs and how they actually interact.

    Class Libraries



    Till now, we have seen that in all of our programs, we have include some header files using include keywords. Actually what happens at the backend is we are referring to some already built C++ library. A C++ library is a compiled form of C++ classes. For instance when you write #include <iostream> in your code, actually you are telling the compiler that you want to use iostream class library functions in your code. Compiler come with some built in class libraries which they place in a special folder called include. This include folder is located deep down in compiler’s directory. In .NET platforms, class libraries come with extension .dll which stands for dynamically linked libraries. It means that when you refer to the class libraries, compiler doesn’t link your code with the library. Actually what happens is that when you run your program, compiler dynamically links the code from those libraries to your program’s code.

    Initially, in structural or procedural programming languages, functions were written in separate files and those functions were called in the main files using include keyword or some other referring keyword. But, since the advent of object oriented programming, programmers started to write classes in separate files. These compiled form of such separate documents that we refer in our programs are called class libraries.

    Class libraries have numerous advantages. They are ready made module encompassing complex functionalities which help reduce programmer’s problems. Programmers only have to combine these class libraries, add their own functionality and achieve desired programming objectives. C++ has thousands of built in and third party class libraries and their number are increasing exponentially. Some of these libraries come free and are open source where as others are commercial. You can also write your own class libraries and upload it to some source for free or for some price.

    Interface



    In order to interact with classes written by other programmers, a mechanism is required. In C++, this is achieved via a file called header file having extension .h. Header file basically contains the information about the classes or the functions that a file contains. The information in header file has to be public due to the reason that is accessed by the programmer who wants to incorporate class library’s code into his code. This header file is known as interface. Suppose we name the code written by developer is called the developer’s code where as those written by me or you are named as the programmer’s code. We want to incorporate the developer’s code into ours programmer’s code. This header file acts as a bridge between the two codes. Actually when we write #include <classname.h>, we are not directly referring to the functionality of the class, actually we are referring to the associated header file. Another reason why programmer provides public functionalities is because they do not want other to pirate their code or modify it without the prior permission of the actual developer.

    Implementation



    Implementation file is actually the file which contains the code written by the developer or as aforementioned the developer’s code which we access using the header file. The implementation is often times hidden from us so that we do not modify this piece of code.

    Now, we have seen three fundamental concepts in multi-file programming in C++. We will give you a more practical demonstration of how actually multi-file programming works. We will explain the concept with help of following examples.

    Note: We will be writing our code in Visual C++ in Visual Studio 2010.

    We will create a win32 console application. If you look at the solution explorer, you will see that application have some folders.

    [​IMG]

    If you look at the above figure, you will four folders. The folders that are of our concern are the source files folder and the header files folder.

    What we are going to do is, we will have three files in our application. One is the main.cpp which will be a class file. We have been using main.cpp in our previous programs. We will have another file named Mathematics.cpp which will be another class file. And the third and last file will be mathematics.h which will be a header file and will be used to communicate between the main.cpp and Mathematics.cpp.

    So, what we have are three files as follows.
    • main.cpp
    • mathematics.cpp
    • mathematics.h
    Before, explanation of the code in above three files, follow these three steps.

    1. Add main.cpp

    This will be the file containing the main function as we have done previously. In all our programs we have this file because this is the point where compiler enters the code. Main.cpp will contain following code. If you do not previously have added this file to your project solution, right click on the project name or the folder named source file in the solution explorer and click on add new item. Add class from the list of items and name it main.cpp. The file will be added to solution explorer. Paste the following code in main.cpp.

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    #include "Mathematics.h"
    int main() {
    	int num1, num2, result;
    	Mathematics maths;
    	cout <<"Enter the first number:";
    	cin>>num1;
    	cout<<"Enter the 2nd number:";
    	cin>>num2;
    	result = maths.add(num1, num2);
    	cout <<"\nThe result of adding two numbers is: "<<result<<endl;
    	result = maths.subtract(num1, num2);
    	cout <<"The result of subtracting two numbers is: "<<result<<endl;
    	result = maths.multiply(num1, num2);
    	cout <<"The result of multipltying two numbers is: "<<result<<endl;
    	result = maths.divide(num1, num2);
    	cout <<"The result of dividing two numbers is: "<<result<<endl;
    }
    For now, just be relaxed, I will be explaining this code later. Just copy this code into main.cpp.

    2. Add mathematics.cpp

    This will be the class which contains the mathematical functionalities: Add, Subtract, Multiply and divide. Remember, in some of our previous tutorials we have defined all these functions in our main.cpp. Again, left click on the project name or the source files folder and add a class. Name this class mathematics.cpp and add following code in that file.

    Code:
    #include "Mathematics.h"
    int Mathematics::add(int num1, int num2) {
    	return Mathematics::result = num1 + num2;
    }
    int Mathematics::subtract(int num1, int num2) {
    	return Mathematics::result = num1 - num2;
    }
    int Mathematics::multiply(int num1, int num2) {
    	return Mathematics::result = num1 * num2;
    }
    int Mathematics::divide(int num1, int num2) {
    	return Mathematics::result = num1 / num2;
    }
    3. Add mathematics.h

    This is the header file we talked in some of our last sections. This file acts as a bridge between the main.cpp and mathematics.cpp. For now, just right click on Header files folder in solution explorer and add new item. This time choose header file. Name the file mathematics.h and add following code in the file.

    Code:
    #ifndef MATHEMATICS_H
    #define MATHEMATICS_H
    #include <iostream>
    class Mathematics
    {
    	int result;
    	public:
    	int add(int num1,int num2);
    	int subtract(int num1,int num2);
    	int multiply(int num1,int num2);
    	int divide(int num1,int num2);
    };
    #endif
    
    After you add all the three files, your solution explorer should look like this:

    [​IMG]

    Now come towards the files.

    First we will discuss the Mathematics.h, the header file. The file starts with preprocessor directives
    Code:
    #ifndef MATHEMATICS_H
    #define MATHEMATICS_H
    
    The above lines tell the compiler that it only has to create single version of the header file that will be used to communicate with Mathematics.cpp. Next, we have simply import the iostream class and have defined a class Mathematics in this header file. This class contains one variable of type integer, named result and four function declarations. Note, we have set the scope of the methods to public because we will access these methods from main.cpp. Another very important thing to note here is that we have not provided any implementation for the functions in header file. We have only declared the functions. In previous section we discussed that header files are actually public interface to access the functionality from the code in some other files, therefore; actual definition or implementation of these methods will be in another file named mathematics.cpp.

    Now come towards mathematics.cpp file. In this file we have provided definitions for the functions we declared in the header file. An important thing to notice here is that we have included mathematics.h file in this mathematics.cpp file on the top. This is because mathematics.h file is glue and any file wanting to interact with other file through the interface of mathematics.h has to import this file. You would have noted that instead of enclosing the header file in <>, we have enclosed it in “”. This is due to the reason that to access the files that are in the same directory “” is used. Whereas predefined class libraries and header files are included in compiler’s include directory therefore in order to access those files we use <>. You can find the files in the project folder. They will all be in same directory.

    Another important thing worth noticing in mathematics.cpp is that we have not defined class in this file. We have only defined functions. Therefore, in order to state that the function belonged to the class Mathematics in header file, we prefix Mathematics followed by scope resolution operator :: followed by the function or variable name as shown in mathematics.cpp.

    Now, come towards our main file. Here after including built-in class libraries, we have included “mathematics.h”. This line of code let us access the Mathematics class and its corresponding arithmetic functions and result variable in mathematics.cpp file.

    Inside, the main method we declared a variable math of class Mathematics and have performed mathematical operations using this file. You can see that here math variable will act like variable of any built-in class.

    This way we have successfully organized our mathematical program into two files. If we want to further add any functionality, we will have to add it simply add it inside the mathematics.cpp and will update the interface mathematics.h. Apart from using these mathematical functionalities in main.cpp, we can use the code in this file in any other file by simply including mathematics.h. When you compile the above code the output will be as follows.

    [​IMG]
     
    Last edited by a moderator: Jan 21, 2017

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice