How C++ works
The basic workflow of c++ code is: source file-> compiler -> executable binary file. But how do we get to the executable binary file from source code?
Let's see a c++ code first:
What is in the Source file?
The first thing we see in the above code is: “#include<iostream>” this is a preprocessor statement. Whatever starts with “#” is a preprocessor statement. When a compiler gets a source file, it preprocesses all the preprocessor statements. Then we have “include”, it finds the file “iostream” and takes all of its contents and pastes them into the current file. This is called a header file.
Then we have the “int main()” function. It is the entry point of the application. So, when we run the application the computer starts executing code that begins in the main function. When the program is running the computer executes the lines of code in order. The first thing that will be executed in the above code is “std::cout << “Hello world” << std::endl;” and then “return 0” , as the return type of main() function is int, we are returning 0 but if you remove this return statement our program will still run fine because for main function if we don’t return anything compiler just assume we are returning 0(this happens only for main function, in any other funtion we have to explicitly give a return statement if the return type is not void).
And by the way, the reason we had to include the file “iostream” is because “cout” needs a declaration(cout is defined inside the iostream file). In the cout statement we have this “<<” , these are overloaded operators. So, in this case, we have to think of them as functions(i.e print() method in any higher-level language). Here, we are pushing the “Hello world” in the cout to print it to the console and then we are pushing “endl”, this endl tells the console to go to the next line.
Source file to executable binary file
To get to the executable binary file from the source file, we have to go through a few stages. First, the preprocessor statement “#include<iostream>” get evaluated before the file is compiled. After evaluating the preprocessor statements, our file gets complied(header files don’t get compiled).
The cpp file gets compiled into an object file(i.e file with (.obj) extension). Then when we run the code linker turns the object file into an executable file(i.e file with .exe extension). This is the output window that we get when we compile and run c++ programs.
However in this case, as we have only compiled one file there is no actual linking happening. But, if we compiled a c++ project where there were multiple cpp files then each of those cpp files would get compiled and we would get object files for each of them and then the linker would link all the object files together and make one exe file.