Build a C++ Program that Have Multiple Source Code Files
In C++ generally, we saw only a single file program but what if we have multiple source code files and we have to build a program by using all these files? Let’s see how we can build a C++ program with multiple source files without including them as header files.
Use two or more source code files in C++
There are two methods to use two or more source code files in C++ as mentioned below:
- Using header file
- Using -gcc commands
1. Using header file
#include<iostream> // Here all basic commands can be used using this files
So, how to use another file let us check with an example.
2. Using GCC Command to Build C++ Program
In this method, we will use the gcc command for running the program because of which we bind both the programs together while running. But, before running the program let’s check how C++ programs work.
Working on C++ Program
Firstly we need to get an idea of how to compile a C++ program with GCC commands. It goes from the following steps :
- Preprocessing: only comments are removed from the source code and header files code is pasted in the file also macros are placed where they are used
- Compiling: texts are converted to machine code but function calls are not mapped with function definitions.
- Linking: the mapping between function calls and function definitions happens as its name suggests ‘linking’. It links the function calls and function definitions
At the linking phase, we have to add all the compiled C++ files (object files) so that the linker links all the files and executables can be formed.
Command to build a C file with more than one C source code file
g++ -o main firstFile.cpp secondFile.cpp
By using the above command we can build a C++ executable. We can add multiple files as arguments in the given command.
Please Login to comment...