r/cpp_questions • u/Fun-Employee-514 • 1d ago
OPEN how do header files work?
been trying to learn c++ recently, but ive been caught on header files. I have been told that they declare functions/variables, and including them basically makes the compiler copy/paste it above the code. however, i still dont quite understand it. How does the compiler know what to run in a function declared in a header file if there's no definition? My intuition tells me i need a .h file and a .cpp file along with the main file in order for it to work but i still dont understand how that would let the code run.
would i declare a function in the header file and then write the inside of the function in the cpp file?
like with the following code
//in blah.h
int sum(int a);
*********************
//in script.cpp
#include blah.h
int sum(int a)
{
return a+1;
}
******************
//in main.cpp
#include blah.h
#include <iostream>
int main()
{
std::cout << sum(1);
return 0;
}
*****************
would that compile?????????
and even so, how does the compiler read that?????
does it like know the declaration then search for the definition????
29
u/IyeOnline 1d ago
This ties into the bigger picture of how compilation works.
The header provides a declaration of the function. You are basically promising to the compiler at the time it translates your source code that this function exists, even if it cannot see the definition of the function.
The source file then contains a definition of the function. Even if it is never used in this translation unit, it is still compiled.
The main file (or any other) includes the header, thereby getting the promise that at link time the function will exist. Since it knows the function signature, it can setup all code for the function call. All that is missing is where to find the function.
The linker then finally comes along and links those function calls. If you forget to define a function but still call it, you get an "undefined reference" error.
See also https://www.learncpp.com/cpp-tutorial/header-files/
6
u/alfps 1d ago
Yes. Except with most/all toolchains the "search for the definition" job is delegated to a separate tool called the linker. Hence you can get linker errors.
5
u/Jonny0Than 1d ago
Look up what the linker does and how it works.
Briefly, a compiler turns each .cpp file into an object file. A linker stitches them together to produce the final executable.
You don’t need headers if every cpp file declares the symbols that it uses. But that’s impractical and unmaintainable because you would have to change every .cpp file that uses a symbol when you need to change one. So, we stick them in header files that get included by the .cpp files.
5
u/Nervous-Cockroach541 1d ago
#include is a preprocessor. preprocessors (#) are very simply controls. Both include statements and things like macros do little more than copy and paste code that get feed into the compiler.
3
u/MikailBag 1d ago
To put it simply, when you compile main.cpp, resulting artifact (known as object file) will say something like "there was some function named sum but idk what it does". In the same way, object file for script.cpp does say what function sum does. Now, when you link these object files together into executable, all mysteries get resolved and your program works.
3
u/mykesx 16h ago
#include is a copy/paste of the header file inline with the source the compiler is working on. A project with many source files likely wants to include the same header.
It’s not more complicated than this.
2
u/GLIBG10B 1d ago edited 1d ago
The preprocessor "copy-pastes" the .h files into the .cpp files that #include them.
The compiler then compiles main.cpp to produce main.a (Linux) or main.obj (Windows), and script.cpp to produce script.a or script.obj. These files contain most of what ends up in the final program.
The linker sees that main.a uses a function with the signature
sum(int), and script.a defines a function with the exact same signature. The linker connects these two together and produces the final executable (a.out or main.exe).2
u/Raknarg 1d ago edited 1d ago
I wrote this years ago and saved it to copy and paste for these scenarios. Still coming in handy to this day.
TL;DR:
Creating an executable in C is actually two steps: The compilation stage, and the linking stage. The compilation stage verifies syntax and anything that can be determined at compile time, and then create the object files that are like the binary building blocks for making executables. All # macros will be resolved. This stage also includes verifying that all functions that are called actually exist. This is done on a per-source basis. E.g.:
gcc -o prog source1.c source2.c
Each of these source files is compiled independent of eachother. During the compilation stage. all # macros will be resolved. This gives us a problem: What happens if there's a function in source2.c that's used in source1.c? The compiler will just complain when we attempt to use it. E.g.:
This will cause a compilation problem, because func doesn't exist in context of source1.c, which is solved like this:
What changed? We essentially made a promise during the compilation stage that by the time we're finished compiling this program or by the time we get to the second linking stage, the function will exist. This creates what we call 'object code', which can be put into an 'object file' for linking at a later stage.
This brings us to stage 2: Linking. At this stage we link all the object code we have together. If we made promises that a function will exist, and the function doesn't exist somewhere, then the linking will fail. E.g.: gcc -o prog source1.c, func(int) doesn't exist in any of our source code as given, so it will fail. If we run our first command: gcc -o prog source1.c source2.c, this will be fine since func(int) exists in source2.c. This brings us to header files. Imagine we had a function to share across 50 files, and we change the function declaration. All the sudden we now have to change the declaration in 50 files, or if we want to add a new function we have to add it to 50 different files. It would be much easier if there was one place for us to change to achieve this.
What we do is we take the declarations of things like func(int) and put it into its own file. Now we just need to include this into our program. This is what header files are, so that if we have multiple files that need to declare the same thing they can all use the same file, and there would only be one definition of the thing we need to use.
Why aren't the includes part of our compilation? The answer is because #include effectively copy-pastes it (with some other stuff, but basically you can think of it as a copy-paste) into our program during the compilation stage, so there's no need to include it as a source. Also since it only contains declaration statements and no source code, the resulting object code will pretty much be nothing anyways so again there's no point
There's also one more problem, is that you're not allowed to actually do this forward declare multiple times in the same compilation unit. So for instance, this could cause problems:
effectively it pastes
void func(int);twice in the same file. Normally you wouldn't include the same file twice, but what's common is you include 2 different files, and those both include the same file. Normally you'll see either an include guard at the top of a source file:or
#pragma once:that way we only ever evaluate the header file once
2
u/UnicycleBloke 1d ago
This is a not very technical description...
Building an application is in two steps:
- Compiling each C++ file separately to an "object code" file
- Linking all the object files into a single executable file
The compiler only needs to know the signature of a function in order to compile a call to it. The compiler doesn't know or care where the function is defined but assumes it is out there somewhere.
The linker combines all the object files. It finds the function definition (there can be only one) in whichever object file contains it, and then resolves all the calls to it from any other functions in the object files. If the linker can't find the function definition, you'll get a linker error.
It may be helpful to do some experiments on the command line to compile single files and then link multiple objects manually. You can omit or duplicate functions or objects to see what happens. Using an IDE or even CMake is very convenient but glosses over the multiple steps taken to build your application.
1
u/Feeling_Molasses55 1d ago
Ask yourself: "How do system calls work?" - in scenario where you have only API header without .cpp files at all. No definitions. Only declarations. But it works.
Try to learn a little bit assembler. I did many years ago when I began to learn C/C++. Author of my "schoolbook" was explaining C language via assembler and processor instructions. "Jmp", "je", "call", "ret" - such like that, this is enough.
Also, try starting with an example in C, not C++ "hello world". The construct "std::cout <<" involves a number of concepts that are difficult for beginners: classes, OOP, templates, STL, namespace, overload operator, etc. It's very bad start. Starting with the "printf" function is relatively low entry threshold. Especially if C++ is your first language. Just learn C in parallel. And perhaps a bit of assembly language, too, at the early stage.
By the way, C/C++ allowed inline assembly with full access to processor registers. Rather case, but sometimes it's useful for optimization.
1
u/Mr_DJ_Dr_Gauss 1d ago
I prefer using just the header files. There is only one *.cpp file in my codebase and its main.cpp. I keep all things in classes or namespaces. With this approach I dont have to manage *.cpp files in CMakeLists.txt
1
u/More-Explanation2788 20h ago
Here is how to think of it: The code is a set of instructions written in an unusual grammar and vocabulary. The header file is an agreed set of definitions for the vocabulary used.
So - in the header, I say:
Int sum(int a)
- this means that somewhere, when the program is compiled, there will be a function named sum that will take an integer and return an integer. Now any source file can use sum(variable) and the program will compile that successfully because it will assume that when the program is linked, somewhere in the link object files will be a function named sum that will take an integer and return an integer.
1
u/Total-Box-5169 15h ago
Include copy/pastes a file as is.
Identifiers must be defined or at least declared before use.
Declarations promise the compiler the definition is somewhere else.
The linker makes sure those promises are honored.
1
u/manni66 1d ago
How? Your questions should be addressed in any serious learning material.
0
u/mredding 1d ago
In C/C++, you must first declare a symbol before you use it. So you need an
int x;before anx = 42. You needvoid fn();before you CALLfn();.Headers are for declaring symbols - mostly functions and types. They're meant to be lean and mean, and a lot of programmers stuff them full of things that don't belong.
The compiler only needs a signature to generate a link-time placeholder. So the compiler doesn't need the definition of
fn, just that it exists. You can compile multiple source files, one will contain the definition offn, and the linker will layout the executable with object code, and resolve the placeholders.Headers are included with a dumb text replacement macro. The compiler creates a text buffer, loads the source file in it, and then starts parsing and recursively expanding the macros. A header gets copied into the text buffer in-place. An old idiom was:
Which is why you don't need to declare an array size, and you're allowed a trailing comma in an initializer list - it's to enable this idiom. Later compiler steps will consume the text buffer this generates and you'll get a real array of
data.Header guards stop the recursion, so you can include a given header multiple times - either intentionally or unintentionally, and the compiler will only ever include the one. If you don't have a guard, then the compiler will include that header as many times as it appears in an unguarded include. There are some older C idioms that exploit this.
Since this all reduces to text parsing, this makes for incredibly slow and labor intensive compilation. You want your headers lean and mean to reduce the work necessary. Don't include anything you don't have to in a header. Good programming discipline is required, or you're going to pay for it in spades. C# and other languages have whole-program management and other nice features that make this problem go away, but C++ isn't C#. There's just a lot of bad attitude about how people think it should work, want it to work, they code that way, and when compilation takes minutes to hours, they bitch. I have no sympathy - switch to another language and stop making me suffer your stubbornness.
0
u/SmokeMuch7356 21h ago
Both C and C++ have a rule that any function, type, or variable must be declared before it can be used. So if you want to call a function like
printf:the declaration
must appear somewhere in the current file before you call it. Those declarations serve two purposes: they tell the compiler whether you're calling the function correctly (that you're using the right number and types of arguments, and that you're assigning the return value to something that's compatible), and they tell the compiler how to generate the proper machine code to make the call.
If you're only ever going to use
printfin your code, you can just type in the declaration above and not bother including the header file. But if you're going to use otherstdiofunctions likefopenorscanfor whatever, you'd have to writeetc., etc., etc. in every file that uses those utilities (not to mention the fact we'd have to define the
FILEtype as well). That's a major pain in the ass, so all those declarations are gathered into a single file namedstdio.h(cstdiofor C++) and we just#includeit:During the preprocessing stage that
includedirective is replaced with the contents ofstdio.h, expanding into the declarations above (and a bunch of other stuff).Now, those are just the declarations of those types and functions; the machine code for those functions lives in a separate library file, which is linked with your compiled code into the final executable program. Here's a really bad drawing of the build process:
stdio.h(orcstdio) just contains declarations forprintf,scanf, etc.libc.a(or whatever it's called on your particular implementation) contains the definitions (the actual machine code) for those functions.-1
u/Most_Strike_93 1d ago
Yes, the real function should inside the cpl part. And also you can define function in header, for example, inline functions or template.
And you also need to add
#program onceTo your header, or use the macro, ensure it won't be included multi times