6 months, 2 weeks ago.
Do I need header and C++ files both?
Hello, I am a junior C++ developer and I have a questions about files for classes.
A lot of libraries contains two files for class: header and C++. I found that format uncomfortable for me, need to change in two places instead one. I am just creating header and have no any troubles with that. But I think I don't know about that part enough to review is that way good.
Is that's just preferred by developers or it has some pattern sense? Where I can read about that if that's some pattern?
6 months, 2 weeks ago.
The compiler will compile each .c / .cpp file once. These files are then linked together to create the end program.
When the compiler runs it first looks for any #include lines in the file replaces them with the contents of that file.
So if you put all of your code in the header and then #include that file in two different .cpp files then you will end up with the same functions in two different places. This will then cause an error when linking because it doesn't know which one to use.
The header only contains the declarations, it tells you what the library contains but not how it's implemented. This is everything the compiler needs to know to check for syntax errors and that functions exist but doesn't actually generate any code when compiled since it doesn't contain any functionality. The main file then contains the details of how that functionality is achieved and is only compiled once. This is a standard rule for c/c++ you can declare something in as many places as you like (as long as they are consistent) but you only ever implement it in one place. That's one place after allowing for header files being #included into lots of places.
All of this does mean that if you change/add a function definition or variable you do need change both files. But it makes compiling a lot faster and simpler (c is an old language. keeping the compile process simple was far more critical back then). It also allows tricks like if I change myLib.cpp when recompiling I only need to recompile that one file and can then link it with the previous compilation results for the other .cpp files. I only have to recompile the other .cpp files if myLib.h has changed. For large projects this can give a huge reduction in compile time.
It also has the advantage that when using a library you should only need to look at the header file to find out what it can do and so don't need to dig through the full code to find what you need.
So the short answer is that you need to stick with two files, this is a fundamental design feature of c/c++. If you put all your code in the header then if only one other file includes that header it will still work but as soon as two different files include that header your program will fail to compile.