C++ Creating Header Files

In C++ header files are pre-written codes/Functions saved as files with .h extension generally. These are pieces of code that you can reuse in your programs by importing that header file.

In C++, we use #include command to import any header file. For creating a new header file, we need to write a piece of code and then save it as .h extension.

Example


int sum_of_num(int a, int b)
            {
            return (a + b);
            }
            

After saving that code with a name and .h extension, we can include that piece of code using #include command in our program. For example, assuming we saved our program as sum.h.



  #include "iostream"
  // Including header file
  #include "sum.h"
  using namespace std;

  // Driver Code
  int main()
  {
    // Given two numbers
    int a = 13, b = 22;
    // Function declared in header
    // file to find the sum
    cout << "Sum is: "
    << sum_Of_num(a, b)
    << endl;
  }
            

Output:


sum is:35

As you can see after importing our header file, we can access our function sum_of_num from that header file and can reuse that.






© Copyright 2022 Advanced PLC. All rights reserved.