This question already has answers here:
What should go into an .h file?
(12 answers)
Closed 2 years ago.
I have searched almost every website I could, but nobody has been able to answer my question. Basically what I ask, is what exactly should I place in a header file? I know of function declarations, but are variable declarations in a .h file also a thing? I need to know what the "tradition" or the "usual method" is of usage of header files.
EDIT : If this helps, I just recently started C++ and my objective with learning this language is an opportunity to get into the industry, mainly gamedev, and I need to know what the proper way of doing stuff is. Hence the question.
Header files conventionally contain declarations of entities that you wish to share between translation units.
That usually means class definitions, type aliases, and function declarations.
A translation unit, very roughly speaking, is "a .cpp file".
So, if you use a function in a.cpp, and you also use it in b.cpp, a declaration for it needs to be available in both translation units, and the best way to do that is to write it once in a header file, then include the header file in both .cpp files.
That's it.
While it's possible to declare variables in a header file, it's rare to do so. For starters, you'd want to put extern on it to make it not a definition (you don't want multiple definitions!). At that point, you have to ask yourself why you're not using a class.
Related
This question already has answers here:
How to make closed source for the library written with template in C++
(3 answers)
Closed 6 years ago.
C++ Compiler needs to have access to the implementation of the methods in order to instantiate a template class. Hence we need to either include the definitions of a template in the header file that declares that template or define them in header files. But I want to hide the implementation (definitions) of my functions from my users due to many reasons and want to ensure that they have only access to the function declarations. Is it possible to do so while using templates in C++?
This is usually done (for eg) in boost by creating a directory hierarchy impl and detail.
impl will usually have the implementatios for the exposed API member function while inside the detail as you might have guessed, has the gritty details which you do not want to expose. This system is fairly well understood by the C++ developers.
As an example:
my_service.hpp
impl/my_service.hpp
impl/my_service.ipp ( OR )
detail/my_service.ipp
So, the idea is to split the header files and provide the users to only include your top level header file which will internally include the other files.
But nobody is stopping the users to include the impl header file as well directly. If you want to avoid that too, then you can do something on the lines of Prevent header from being included in some files, in compilation time?
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm working with functions.
Is it good practice, that I write the function in another .cpp file, and I include it in the main one?
Like this : #include "lehel.cpp".
Is this ok, or should I write the functions directly in the main.cpp file?
A good practice is to separate functionality into separate Software Units so they can be reused and so that a change to one unit has little effect on other units.
If lehel.cpp is included by main, this means that any changes in lehel.cpp will force a compilation of main. However, if lehel.cpp is compiled separately and linked in, then a change to lehel.cpp does not force main to be recompiled; only linked together.
IMHO, header files should contain information on how to use the functions. The source files should contain the implementations of the functions. The functions in a source file should be related by a theme. Also, keeping the size of the source files small will reduce the quantity of injected defects.
The established practice is putting function declarations of reusable functions in a .h or .hpp file and including that file where they're needed.
foo.cpp
int foo()
{
return 42;
}
foo.hpp
#ifndef FOO_HPP // include guards
#define FOO_HPP
int foo();
#endif // FOO_HPP
main.cpp
#include "foo.hpp"
int main()
{
return foo();
}
Including .cpp files is only sometimes used to split template definitions from declarations, but even this use is controversial, as there are counter-schemes of creating pairs (foo_impl.hpp and foo.hpp) or (foo.hpp and foo_fwd.hpp).
Header files (.h) are designed to provide the information that will be needed in multiple files. Things like class declarations, function prototypes, and enumerations typically go in header files. In a word, "definitions".
Code files (.cpp) are designed to provide the implementation information that only needs to be known in one file. In general, function bodies, and internal variables that should/will never be accessed by other modules, are what belong in .cpp files. In a word, "implementations".
The simplest question to ask yourself to determine what belongs where is "if I change this, will I have to change code in other files to make things compile again?" If the answer is "yes" it probably belongs in the header file; if the answer is "no" it probably belongs in the code file.
https://stackoverflow.com/a/1945866/3323444
To answer your question, As a programmer it will be a bad practice to add a function when cpp has given you header files to include.
Usually it is not done (and headers are used). However, there is a technique called "amalgamation", which means including all (or bunch of) .cpp files into a single main .cpp file and building it as a single unit.
The reasons why it might be sometimes done are:
sometimes actually faster compilation times of the "amalgamated" big unit compared to building all files separately (one reason might be for example that the headers are read only once instead for each .cpp file separately)
better optimization opportunities - the compiler sees all the source code as a whole, so it can make better optimization decisions across amalgamated .cpp files (which might not be possible if each file is compiled separately)
I once used that to improve compilation times of a bigger project - basically created multiple (8) basic source files, which each included part of the .cpp files and then were build in parallel. On full rebuild, the project built about 40% faster.
However, as mentioned, change of a single file of course causes rebuild of that composed unit, which can be a disadvantage during continuous development.
This question already has answers here:
Why have header files and .cpp files? [closed]
(9 answers)
Closed 6 years ago.
Comming from a mostly Java background I recently started learning a bit of C++.
I'm trying to create a class that describes a LinkedList. Since I want this class to be something like an external library, so I can use it in other applications, I need it to be declared as a header file.
I understand that from a design point of view C++ needs both a header and a cpp file, where the header will mostly contain declarations and the implementation will be left for the cpp file.
What I don't understand though is what is the actual purpose of the above design technique. The point of being able to quickly go through the header file and read the comments about the functionality of each method seems moot to me, since C++ (or at least my Codeblocks editor) supports the
/** comments like Java so it is much easier to create an object of the class and simply hit the . button to open the methods description menu, and read any description I like in a more orderly and structured manner than going through a header file.
Also I noticed that the program runs fine if put everything inside the header file and completly ignore the cpp file.
So my question boils down to whether I should just implement everything in the header file, or whether this is considered unacceptable C++ coding practice and if so, why.
Headers contain the bare minimum required to be able to use the functionality, since they get to some intermediate preprocessed file. The smaller that file, the easier to compile that unit.
They have to contain structure definitions and function declaration in this sense. This is unlike Java which doesn't require prior declaration in order to use and is a historical artifact which cannot be fixed now. The #include lines really paste the text in the header within the actual C/CPP file (sort of -- the preprocessing, conditional compilation etc have to happen in the headers too)
A number of posts are pretty adamant that source code should not go in a header and that header files should be kept to a minimum. I've been sticking to this with my own code, but I want to use someone else's code to achieve a particular goal (the code is documented here http://ftp.arl.mil/random/).
I notice that this is basically one giant header file which defines a class. Is it OK to leave this in a header file? Should I copy it all to a .cpp file and create a new .h that just declares the functions, structures etc?
If I split it into a .cpp and a .h as I propose, will it work? Or do classes need to be in the header to be accessed by all source code?
Declarations (stating that something exists) that need to be seen in more than one cpp file should go in header files. Declarations that are local to a single cpp file should be in the cpp file itself.
Definitions (providing the body of a function or allocating/initializing variables) should usually go in cpp files, but not always.
The question you need to understand is does the compiler have enough information to do its job if it has seen the header file and not the corresponding cpp file.
For example: you can call a method if the compiler has seen the declaration (the method prototype) -- unless the method is generic (a templated method or a member of a templated class) or inline in which case the compiler needs to have seen the definition (the method body) too.
Therefore normal methods go in cpp files; templated methods go in header files; inline methods go in header files (and so on).
There are other situations in which definitions belong in header files including static member constants. It all comes back to giving the compiler the information it needs one one hand vs minimizing coupling between separate compilable units on the other. Again there are no hard-and-fast rules, just guidelines coupled with the knowledge and experience of the developer writing the code.
.h files are usually shared between many .cpp files.
The global variables and function code should not be in the header files, because it would make duplicates during linking.
Constants, defines, function headers and class declarations are fine in header files. You don't have to declare the same thing multiple times and you can share the definitions between .cpp files.
source code should not go in a header and that header files should be
kept to a minimum.
This is a popular assertion, and while it may generally not be bad advice, you should not draw absolute conclusions from it. Sometimes headers should be minimal and not include definitions. Sometimes the opposite is true. There are reasons why you would do one or the other, but "people say" is not one of them.
Consider the C++ Standard Library. Better yet, consider Boost. Some prestigious C++ experts have said that Boost is the most well-designed C++ library in history. But if you look at the libraries you'll see that they are basically just giant header files for the most part. How does this reconcile with what "they" say?
The point is this: you must understand the reasons why certain files are designed the way they are, and make up your own mind about what is Right and Wrong for each situation.
Should I copy it all to a .cpp file and create a new .h that just
declares the functions, structures etc?
I would say probably not. This sounds like a recipe for a maintenance nightmare to me. It would be my first instinct to use the 3rd party library they way the library's author intended it to be used. That way you won't be off the support grid, and you won't introduce a new set of complications that you will be completely on your own to figure out. Unless you have a specific, provable reason to alter the architecture of the library, don't. "They say" isn't a good enough reason for me.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why can templates only be implemented in the header file??
Hi,
I have a c++ project which consists of several header and source files. In order to modify the class with a template, I found that all the method definitions must be included in the header file itself, else resulting in a link-time error. What is the reason for this and how can I get over this ??
Thank You!!
This is intentional. Templates go in header files, end of story. There is no way around it. In order for the compiler to instantiate the template it must be able to see it, which means it must be in a header file. Templates are not like C# generics, where the model allows them to be hidden an essentially instantiated by the linker - templates are much more complicated than that, so they have to live in header files.
In your travels you will find mention of the export keyword, which was supposed to solve this. To cut a long story short, it didn't, no one implemented it (apart from one very brave compiler vendor) and it will soon not be part of C++ any more.