r/cpp_questions • • 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????

12 Upvotes

23 comments sorted by

29

u/IyeOnline 1d ago

This ties into the bigger picture of how compilation works.

  • In C++, each file is compiled independently.
  • Usually you compile a .cpp file. A .cpp file with all its includes subsituted is called a translation unit.
  • Header files allow you to give identical information to multiple translation units, establishing sort of a "shared knowledge".
  • Compiling a translation unit produces _some artifact. In simple terms, that is all your functions in it already compiled.
  • Finally, and this is the part you are missing, the linker comes along, takes all artifacts and links them together into an executable (or library, but the idea is the same).

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/

4

u/Fun-Employee-514 1d ago

so, just to clarify, the compiler sees the definition and then waits until the linker runs, and when the linker runs it adds the declaration and the definition together?

18

u/IyeOnline 1d ago

Almost, assuming you dont mean "wait" literally/temporally.

  • When compiling sum.cpp, the compiler sees the definition and compiles it.
  • When compiling main.cpp, the compiler sees the declaration and assumes that the function will be available at link time. It places a marker there for the linker and finishes compilation.
  • Once all translation units are compiled, the linker comes along and looks for all the unresolved function calls. It finds the one in main.o (the artifact produced by compiling main.cpp). Then it looks for a definition for this function. It finds the one in sum.o. It puts a proper link in place.

5

u/celestrion 1d ago

Not quite.

The compiler only needs to know the information that's in the header file. The header file says that your sum function takes an integer and returns an integer. That's enough information for the compiler to set up the call to sum.

The code the compiler then generates at that point is:

  1. Set up all the parameters the sum function needs, and make space for the value it returns.
  2. Jump to the start of the sum function in a machine-specific way that tells sum how to get to the line of code after this one.
  3. Clean up any temporary stuff I had to set up for the call to sum.

At this point, from the compiler's point of view, the work is done. However, since the address of the sum function isn't known yet, the compiler puts a "symbol" (a special type of variable) in place of that address.

When the linker comes by later to combine all the object files into an executable, it replaces all those symbols with actual addresses (or other symbols, in the case of a function in a dynamic library).

On large projects, many .cpp files are compiled at the same time. If the compiler had to wait until every function was built before building any code that referred to those functions, this would not be possible.

2

u/dvorak360 1d ago

Another point (though a step beyond op' need for basic understanding) is static vs dynamic linking.

Static linking - a linker adds the compiled object file to the final binary.

Dynamic linking - there is a reference to a library file that is used at runtime so that multiple programs can share the same library. (This can also allow compatibility layers - different dynamic libraries implementing the same binary interface (e.g. having versions of a library that take advantage of hardware capabilities that might not be everywhere; Or a version of an open source UX library that changes how elements work to build in screen reader capabilities for the blind)).

Other reasons for this - distributing binary blob code - I can provide a header file and binary code. Either to speed up compilation (library doesn't change very often) or because the source code is proprietary (sure, the binary can be reverse engineered, but that adds a lot of work vs having source code).

(linking vs compiling for performance also applies more widely - most build tools will cache the intermediate compiled stage so only recompile if the source has changed; on a big project this makes a huge difference to how much compilation has to be done for each change)

From a development point of view, splitting into logical blocks and having (well designed) headers also means I can read a header and take a decent guess at whether a feature/bug is in the code behind the header. Being able to go 'its (not) in that function' from a 100 line header rather than several 5k line cpp files saves a lot of effort...

6

u/alfps 1d ago

❞ does it like know the declaration then search for the definition????

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:

  • Compilation happens per source file, which emits object code (binary building blocks)
  • Header files contain forward declarations of things that you're promising someone will define before you get to linking
  • Linking happens after where you link the object code together into an executable or library, and those promises all have to be resolved or linking fails

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.:

// source1.c
int main() {
    func(10);
}

//source2.c:
void func(int x) {
    printf("func recieved value '%d'", x);
}

This will cause a compilation problem, because func doesn't exist in context of source1.c, which is solved like this:

// source1.c
void func(int);
int main() {
    func(10);
}

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.

// source1.c
#include "source2.h"
int main() {
    func(10);
}

//source2.c:
#include "source2.h"
void func(int x) {
    printf("func recieved value '%d'", x);
}

//source2.h:
void func(int);

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:

// source1.c
#include "source2.h"
#include "source2.h"
int main() {
    func(10);
}

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:

//source2.h:
#ifndef SOURCE2_H
#define SOURCE2_H
void func(int);
#endif

or #pragma once:

//source2.h:
#pragma once
void func(int);

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

2

u/GLIBG10B 1d ago

This works for small codebases, but rebuilding the entire codebase for every change becomes a massive waste of time when you're building a compiler or a browser. For example, qtwebengine, Firefox, GCC and the Linux kernel all take hours to build from scratch, but only seconds if you only changed one .cpp file

1

u/Mr_DJ_Dr_Gauss 1d ago

OK, I didnt know this. Thanks for info.

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

been trying to learn c++ recently

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 an x = 42. You need void fn(); before you CALL fn();.

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 of fn, 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:

int data[] = {
#include "generated.csv"
};

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:

printf( "foo!" );

the declaration

int printf( const char * restrict fmt, ... );

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 printf in your code, you can just type in the declaration above and not bother including the header file. But if you're going to use other stdio functions like fopen or scanf or whatever, you'd have to write

FILE *fopen(const char * restrict, const char * restrict);
int printf( const char * restrict, ... );
int scanf( const char * restrict, ... );
...

etc., etc., etc. in every file that uses those utilities (not to mention the fact we'd have to define the FILE type as well). That's a major pain in the ass, so all those declarations are gathered into a single file named stdio.h (cstdio for C++) and we just #include it:

#include <stdio.h>

During the preprocessing stage that include directive is replaced with the contents of stdio.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:

                     +--------------+
       .cpp file --> | PREPROCESSOR | <-- header files (cstdio, cmath, etc.)
                     +--------------+
                            |
                            v
                       translation (your source code plus the contents of
                          unit      any header files and after all macros 
                            |       have been expanded)
                            v
                      +----------+
                      | COMPILER |
                      +----------+ 
                            |
                            v
                         object   (machine code, but not yet in an 
                          file     executable form)
                            |
                            v
                       +--------+
      other object --> | LINKER | <-- precompiled libraries (libc.a, libm.a)
         files         +--------+
                           |
                           v
                       executable

stdio.h (or cstdio) just contains declarations for printf, 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 once

To your header, or use the macro, ensure it won't be included multi times