I would like to write code in .hpp without separation to .h and .cpp
I did it. I use .cpp only for static class-fields definitions
I would like not to write #include manually ...
I use forward delarations where it possible.
Every my .hpp file containt #pragma once.
But, when my project grows up to 40-50 classes i saw problem of include graph. There are some errors of definitions.
Image with include graph of my project model (like part of mvc) attached.
I used this app for graph generation (can work without MSVS!).
How include graph should look like? Like a tree?
How not to write includes manually, like in C# or Java?
Unfortunately you're possibly using the wrong language. There are some things that are just much in C++ easier when you separate the class definition from implementation. Even with forward declarations you'll probably still wind up with circular dependencies that can only be resolved by moving implementations into separate files.
If you want to write idiomatic Java, just write it in Java. If you want to use the C++ language unfortunately you'll have to work within its constraints.
Let's assume you have a .hpp file per class, then, the include graph is similar to the class dependency graph.
For sake of reusability, a class dependency graph should be acyclic (you can achieve this by using interfaces to "split" cycles).
So, I guess the include graph should be acyclic too.
As for the #include clauses, I'm afraid you have to write them manually. But if your classes are small enough, this shouldn't be a problem (if your classes are so huge you can't figure out what include you need, you've got a design problem).
Just as a small note, splitting your classes into .cpp and .h files not only solves the circular dependency problem, but also might dramatically increase your compilation time.
If you're attempting to write header-only code, you would probably end up with a full rebuild of your project even if one small part of code gets changed.
Header-only code only makes sense if you're designing a template-based library, basically, because template should reside in headers. See boost template library, for example. And also to mention, real application using template libraries still have those .cpp files for their code and that's where the instantiated templates are actually "used".
I highly suggest placing implementation into ".cpp" files and declarations or interface into header files, ".hpp".
When an inline function is changed in a header file, ALL source files that include the header file will be recompiled. When a function is changed in a source file, only the source file needs to be recompiled.
Get the code working correctly and robustly before creating inline functions.
Another suggestion is to make libraries (collection of object files) for source files that are grouped by a theme or are not compiled often (i.e. they work and don't change).
Don't worry about the quantity of files nor the length of the build process. Focus on completing the project correctly, robustly and under schedule. Adjust the build process as necessary. If there is a lot of time in the schedule are the code works correctly and is robust, then make changes. If changing the build process can speed up development time *significantly", then make the changes.
Related
Im new to learning c++ and I was curious as to what the purpose of multiple header files is. Why can't you just have everything in one header file?
The keyword here is modularity:
Modularity is the degree to which a system's components may be separated and recombined.
As others have already mentioned, you can write a program in a single file. Moreover, you can write it in a single line. However, you don't do this because it would then be really difficult to separate and recombine parts of this program, let alone debug it if it doesn't compile.
Why can't you just have everything in one header file?
If you cram everything into single header, every single change to that header will cause recompilation of every file that includes that header. In your case that'll be entire project.
It is easier to manage project, when you have many small files and include them only when they're absolutely necessary.
Headers exist to organize.
For a very simple project, one header file would do just fine. You can even not use headers at all and just write everything in a single file.
But once you grow to a bigger project full of parallel systems, classes that are used in multiple contexts, or simply using 3rd party libraries like OpenSSL or MySQL, you can't simply expect to work putting all this code in a single file with millions of lines of code.
You may also be wondering why not put all and any required header in your project in a single "common.h" and then #include it in every .cpp.
The answer is because each .cpp is compiled individually, so if you limit the headers for each .cpp to only what is required for it, you will decrease both the resulting .obj size and the compile time.
Also, you would be forced to recompile the entire project every time you make a change to any header, instead of recompiling only the .cpp involved.
You can have everything in one header file. You can even have your entire program in one single file.
The benefit of separating things out into distinct, small files is that you compile small parts at a time, and you only need to recompile those parts whose components have changed. You can also put common code into separate files and use those files from separate projects, without the need to copy-paste code across projects. So if you find a bug, you can fix it once and all your projects benefit from the fix.
In addition to all the answers already posted, you may want to consider that C++ has a philosophy of you pay for what you use or, conversely, you don't pay for what you don't use.
If my application needs, say, complex numbers, then I go ahead and #include this functionality. If I don't need it, then there is no reason whatsoever why my code should even be aware that such concept exists.
When I determine that I keep including the same header files over and over again for a given kind of application, I create a master header file which includes the includes, and I just #include that one.
For example:
// #file project.hpp
// #brief provides all the functionality required by `project`
#include<library1.hpp>
#include<library2.hpp>
#include<library3.hpp>
// any type definitions go below this line
and then, in my project
// #file project.cpp
// #brief Implements `project`
#include<project.hpp>
// go ahead and implement project
Other libraries such as boost normally offer a "master" include file such as the one described above to simplify using the library.
Yes, you can have everything in one header file. However, as your project grows, that header file will soon become an unmaintainable and slow-to-compile mess.
For years I've been coding C++ in the standard way, with class declarations in header files .hpp and the function definitions in source .cpp files. Recently I moved to a new company where the code (seemingly influenced by boost coding styles) is entirely coded in .hpp files with one short .cpp file to include the header files and create the object/program binary.
It got me thinking - what are the strengths/weaknesses of writing your code in header files as opposed to writing a .hpp & .cpp file for each object? This assumes our project doesn't create common libraries that are then linked into the program binaries, but instead each program binary is built from the sum of the header files (and one source .cpp file). Is this a new trend in C++?
E.g. Template objects need to be header only, but it could seem a good idea to put non-template classes into header files and then simply include these common project classes in your binary(s). Assuming you're creating a new codebase from scratch, would it mean less linking, which might mean less linking errors and possibly faster builds. Would pre-compiled headers facilities also mean using header files speeds up build time? Or are build times longer because we now need to compile all code when creating a binary rather than linking common shared library objects?
Also note we're not writing an API here (in which case something like the pimpl idiom would give us more flexibility by hiding implementation), we're writing programs to run on a customer site.
Thanks in advance,
Off the top of my head:
Strengths:
implementation visible (more of a weakness, but depends on the case)
no need to export to a library
better chance for the compiler to optimize some of the code
Weaknesses:
implementation visible
slower build time
bloated header files
a change in implementation would require a full rebuild, having the implementation in an implementation file does not (only compile that specific file or library)
In case of circular dependencies, you use forward-declarations and only include the full type in the implementation file. If all you have is a header, this is no longer possible.
I'm sure there are others, I'll edit if I can think of any more.
Header only libraries tend to make the build system easier, and generally you need to care less about dependencies.
On the other hand moving code to implementation files make it easier to control module boundaries and create exchangeable binary modules, which can improve incremental builds. The cost is more "housekeeping".
My hunch is to prefer implementation files, and there are some data points that back me up, like this blog post from the Author of the proposed Boost Networking Library.
Common libraries are one thing, general reusability of code is another. If you want to use some of the code you've written in another project, you may have to copy'n'paste huge chunks of code and then maintain the separate codebases. The compile time will get longer, because the program will be a one big compile unit as opposed to many cpp/h files, where only these, who include modified header file will be recompiled. For instance, full build of application I'm currently working on takes 7 minutes. A recompilation takes ~ fifteen seconds, if the changes are not severe. Finally, the code may tend to be less readable. Header file gives you quick glance of what the class is created for and how to use it. If classes are written inplace, you'll have to unnecessarily dig through the source code.
Looking around at different code bases I see a variety of styles:
Class "interfaces" defined in header file and the actual impl in a cpp file. In this approach the headers look well defined and easy to read but the cpp files look confusing as it's just a list of methods.
The second approach i see is just to put everything in a single class cpp file. These class files contain the definition and actual method impls in the body of the class definition. This approach looks better to me (more like Java and c#).
Which style should I be using?
For all but the simplest programs, style #2 is simply impossible. If you #include a .cpp file with function definitions from multiple other .cpp files, the definitions get added to multiple object files (.o / .obj) and the linker will complain about clashing symbols.
Use style #1 and learn to live with the confusion.
The former - interfaces in header files and class bodies in implementation files. You'll find this causes you fewer problems when working on large systems.
In C++ why have header files and cpp files?
C++ doesn't use "interfaces" they use classes - base/derived classes. I use one file to define class/and its implementation methods if the project is small and separate files if the project is large.
In java, I pack them up into one package then import it once in need.
Since you tagged with c++, go for first style. I don't find it confusing, for a Java programmer, it may seem different, but in C++, you are always going to use this approach.
In fact in my favorite IDE (MSVS), I open header file, and cpp file side by side. Makes looking up prototypes, and class declaration easy.
And when you have a dozen classes; a dozen .h files, and another dozen .cpp file, will make your work simpler. Because, when you want just to see, what a class does, you just open relevant .h file, and take a look at class members, and maybe short comments. You don't need to wade through several lines deep code.
Conclusion : The style options you gave, are option only for a small code, typically single file, with very few methods etc. Otherwise, it is not even a option. (#Thomas has given the reason why #2 is not even a option)
Header (HPP):
The header includes the declarations of your code, particularly function declarations. Technically speaking classes are defined in header-files, but again, the member functions are just declared.
Code in other files will include just this header and retain all necessary information from there.
Implementation (CPP):
The implementation includes the definition of functions, member-functions and variables.
Rationale:
Header-files gives a developer (a external user of your code) a plain overview and just offers the external available code (i.e. easy to read, only the information necessary for users).
Header-files allow the compiler to check the implementation for correctness
Header-files allow the compiler to check external code for correctness
Header-files allow for seperate-compilation. You need to keep in mind. that in former times, computers doesn't have enough resources to keep everything in main-memory during a compilation process. Header files are small, while implementation files are big.
Use #style 1, even for simple programs. So you can learn easily to work with. That maybe look outated today, especially in background of modern Multi-Pass-Compilers. But seperate header-files are even today beneficial. Rumours about the next C++-Standard appeared, as far as I know something like symbol export ( Java or C#) will be possible. But don't nail me down on this!
Notes:
- member-functions which are defined inside a class are by default inline, normally you don't want this
- use always defined guards
If you are developing large project, you'll find the first approach helps you a lot. The second approach may help you in small project. As your project becomes larger, management of complexity is a big issue of software development, and the first approach turns out to be a better choice.
What I do is:
write .cpp files, with the method names prefixed with the class name
in the .h file, create an empty class, with the appropriate name, then use a cogapp generator script, cog_addheaders.py, to insert the declarations, eg:
.cpp file: WeightsPersister.cpp
.h file: WeightsPersister.h
This way I get:
fast compilation (just needs to recompile the .cpp file, unless I change the class interface)
few issues with circular declarations
acceptably low tedious mindless manual work :-)
I'm using C++ and I'm considering putting my function implementation into .h. I know that .h file is for definitions and .cpp is for implementations but how splitting all files into headers and sources will benefit me. Well if my aim would be to create static or dynamic library than of course that would make a difference but I am creating this code for myself and not planning to make a library out of it. So is there any other benefit from splitting source from definition?
The obvious goal is to reduce coupling : as soon as you change a header file, anything that includes it must be recompiled. This can rapidly have a strong impact on compilation times (even in a small project).
You can put almost all code into .h file, it will be header-only library. But if you want more faster partial recompilation, or if you want put some code to shared library - you should create .cpp files.
Depending on the size of your project it will save you compile time and make it possible to know all ressources etc. (unless you put everything into one single file).
The better your header files are organized the less work your compiler has to do to apply changes. Also looking in a small header file to look up some forgotten parameter information is a lot easier than scrolling through a hole cpp file.
One other obvious improvement is in avoiding re-compiling the code for your function in each file that uses it, instead compiling it once and using it where needed.
Another is that it follows convention (and the standard's one definition rule), so others will find it much easier to deal with and understand.
It depends on the size of the project. Up to about 500 LOC,
I tend to put everything in a single file, with the function
definitions in the class. Except that up to about 500 LOC,
I generally use a simpler language than C++; something like AWK.
As soon as the code gets big enough to warrent several source
files, it's definitely an advantage to put as little as possible
in the header, and that means putting all of the function
definitions in the source files. And as soon as the classes
become non-trivial, you probably don't want the function
definitions in the class itself, for readability reasons.
--
James Kanze
As a novice C++ programmer I have always put my classes interface in .h files and implementation in .cpp files. However I have recently tried C# for a while and I really like its clean syntax and way to organize files, in particular there is no dinstinction between headers and implementation, you usually implement a class for each .cs file and you don't need headers.
I know that in C++ this is also possible (you can code "inline" functions in .h files), but up to now I have always seen a clear distinction between .h and .cpp files in C++ projects. What are the advantages and disadvantages of this approach?
Thank you
There's a few ways that separating the two help in C++. Firstly, if you'd like to update a library without changing an interface then having the code in the C++ file means that you simply can update the library rather than the library plus the headers. Secondly it hides the implementation. That is, it forces people to look at your class only in terms of the interface, the thing that should concern them if the code is well written. Finally, there's a sort of asthetic cleanness with interface + documentation that comes with this separation. It's something you have to get used to but after a while it'll feel natural (opinion.)
Don't forget build times.
Putting implementation code in header files makes them more likely to be changed. And changing header files will cause rebuilds of all the CPP files that include them, which in turn increases build times. This can be significant in larger projects.
I am also a fan of keeping the implementation hidden from users of my libraries. Unfortunately this doesn't work for template classes.
My rule of thumb: keep declarations in .H files, keep definitions in .CPP files.
it's cooler to have the symbols defined at one place for the case you wanted to compound C++ with already compiled binaries (typicly when using a library). imagine you need to define external symbols for global stuff in your binaries. if you had .cpp and .h code in the same file you would have to define the symbols for your binaries for every such file. in two files way you could have just the one .h with definitions for binaries and a lot of .cpp files that use it.
The main difference is that something implemented inside a .h file will be placed in every compilation unit that includes that header, this will create redundancy during the compile phase in the final binary executable.. while splitting with .h and .cpp will compile it in a single object file that is later linked against the other objects files by having just one compiled binary code that implements that header file.
In addition if you declare things just inside a .h you are not able to share variables and structures between more other .cpp files..
It's interesting to note that C# seems to be going in the C/C++ direction to some extent recently, with the introduction of partial classes.
The particular advantage of this in the IDE is that the Visual Studio designer will modify the part of the class that deals with visual controls, or data members, and their layout without any worries about mucking up the methods (application logic) that reside in a separate file.
I would echo #wheaties and add a few further items
Compilation is easier (may be it's just me), I've never been able to get compilation to work just right if you modify the header only (as in all the implementation files that have included it). I believe in Makefiles you have to add the dependencies manually which is a real pain in very large scale projects (again could just be me). So if you have your code in implementation files, then changes simply mean recompiling that particular file - very useful when you want to do quick changes, build and test.
Let me re-iterate the hiding aspect, most often you don't want people to know the implementation details due to the sensitive nature of the code, and thus only expose the headers plus the pre-built libraries, and the separation is key here.
Forward declarations, neat trick where you don't need to include the implementation details of a class in the header file if it's not being "used" in any of the code in the header, but then in the implementation file you can include the real header and "it all works nicely" (helps if you have cyclic dependencies - why you have them is different issue!)
On a recent large project the authors of systems I wanted to use had placed a lot of the code in .h files. When including their .h files into my own source it added further dependencies to my file. After including the dependencies for their project I ended up with typedef collisions. If they had separated the code and only placed declarations in the .h file it would have been much simpler. I suggest using posix types and only putting declarations into .h files.
I see that a lot of responses advocate separation, primarily for build-time and implementation hiding benefits. Both are definitely pluses, though I'll argue the counter example: Boost.
Most Boost libraries use a .hpp file with no external linking. The reason is that this is often required in the case of templates, when the compiler must know the argument types from the calling routine. So you might not have a choice if you want to stick with the "modern" C++ approach of shunning classes for templates.
As for the comparison part of .cs versus .cpp/.h I think you need to keep in mind the background the lead architect of C#: Anders Hejlsberg. In Delphi you also don't have the distinction of header and module (ignoring include files for this discussion). You simply have two sections in a unit file initialization and implementation.
The other points were already mentioned.