What is the point in having a header file?

I’m sure this has been asked but what is the point in having a header file. I have learned a lot of C# and am familiar with it. I understand having separate scripts in which you can connect one script to the other but I am not understanding the point in a header file. Is it really necessary? If we ran all the code off one script would it still work? If we had the main.cpp and BullCowCountgame.cpp could we run it just as good or is the header file essential to running the code?

Sorry if this doesn’t make sense or if it seems like common sense but I literally have no understanding of using a header file. Just RIGHT OVER MY HEAD. aha

Not an official definition or anything but “scripts” tends to refer to something that will be interpreted not compiled. You would call these source files.

Technically, no. In the real world it’s unfeasible.

Yes.


C++ supports a separate compilation model. If I have two files A.cpp and B.cpp I can compile them separately even if one uses functions defined in the other.

Say I have main.cpp, calculate.cpp, and calculate.h

//calculate.h
int calculate(int,int);
//calculate.cpp
int calculate(int lhs, int rhs)
{
    return lhs + rhs;
}
//main.cpp
#include "calculate.h"

int main()
{
    int value = calculate(1, 2);
}

Now let’s pretend the function int calculate(int,int) is really complicated and requires lots of helper functions the user of this function doesn’t even know exist and compiling calculate.cpp takes an hour.

Now provided I had the source to calculate.cpp I could just copy and paste it above my code and it would work (provided no name collisions) but now I’ve added an hour to my build times every time I make changes and want to test it.

Using separate compilation, calculate.cpp only needs to be compiled once (or come pre-built) and be linked to. I don’t need to pay for it’s compilation cost every time I make small changes to my code.

Now the header is just the declaration because the compiler needs to be told what calculate is, in this case it’s a function that takes two ints and returns an int. That’s all the compiler needs to know in order to use it.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms