Header File

So far we've written lot of codes. We can write all those code inside a single header file so that it can used in multiple .cpp projects. Header files contains definitions of functions that we can include or import using a preprocessor directive #include. It also gives us the benefit of reusing the functions that are declared in header files to different .cpp files and including a header file is way easier than writing the implementations. There are 2 types of header files in c++, let us study those with definition

So far we used something called #include <iostream> where iostream is a Standard library header file which stands for input and output stream used to take input with the help of “cin” and “cout” respectively. The syntax to include each header file will be different as we use <> for Standard library header files and " " for User-defined header files(Refer below syntax).

CODE

EG 1 . Creating a method inside newly created header file. including it in a different project.

#pragma once
int cube(int number) {
    return number * number * number;
}

Once after writing above code, save header file. Open the current project location where you will find the newly created header file.
Header file location
Create a new Console App project. Inside that folder location copy paste this header file. Now whatever code we written inside this FirstHeaderFile.h is available in newly created project also. The only step what we need to follow here is, we need include FirstHeaderFile.h inside current project using #include. Just follow the below codes to see how to include newly created header file and how to access method present inside it.


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

using namespace std;
int main() {
    cout << "The cube value of 9 is " << cube(9) << endl;
}



(Click Here, For more exercises)