c++header-files

Why I have to use header file in separate file except main file?


The header's file content is put where .h file is used. Why use add.h in add.cpp?

In case without using header file

add.cpp

// There is not declaration int add(int x, int y);

int add(int x, int y)
{
    return x + y;
}

main.cpp

#include <iostream>

int add(int x, int y);

int main()
{
    std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
    return 0;
}

In case using header file

add.h

int add(int x, int y);

main.cpp

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

int main()
{
    std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
    return 0;
}

add.cpp

#include "add.h" // Why use header file here?

int add(int x, int y)
{
    return x + y;
}

add.h

int add(int x, int y);

main.cpp

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

int main()
{
    std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
    return 0;
}

add.cpp

#include "add.h" // Why use header file here?

int add(int x, int y)
{
    return x + y;
}

The output main.cpp will be

main.cpp

int add(int x, int y);
#include <iostream>

int main()
{
    std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
    return 0;
}

add.cpp

#include "add.h" // Why use header file here?

int add(int x, int y)
{
    return x + y;
}

I don't understand why use add.h file in add.cpp file


Solution

  • One reason for including add.h in add.cpp is to make sure that the declarations in add.h are consistent with the definitions in add.cpp. Try changing add.h to

    double add(int x, int y);
    

    In your second example you will get a compiler error, this is guaranteed. But in your first example you will not get a compiler error, you might get a linker error or even a runtime error, but there are no guarantees.

    In other words including a header file in the corresponding cpp file is a safety check to ensure the two files are consistent.

    As you go further will C++ and start to declare classes you will find that the cpp file won't even compile without the corresponding header file. So that's a good reason to get into the habit of always including the header file now.

    Finally it's a good rule to follow that when you include a header file in the corresponding cpp file it should always be the first header file you include. Accross a whole project this ensures that each header file is capable of being independently compiled. In other words you avoid a situation where a header file can only be compiled if another header file is included before it.