For example, in <algorithm>, the function equal_range returns a pair, so can I assume that if I #include <algorithm>, <utility> is #included?
There is never a guaranteed inclusion of header files that other headers depend on. Fortunately, it's common practice (though not certain 100% of the time) that headers are guarded against multiple inclusion -- meaning you can #include them as many times as you wish without causing harm.
You should always include what you need, you cannot rely on all implementations including the same set of headers in another header.
In your example, if a function returns a pair you can be reasonably sure that the pair class is declared, but nothing requires the implementation to include the rest of <utility>.
In fact, it is impossible to implement the standard library using exactly the headers shown in the standard, because there are some circular references. Implementations must split them in smaller parts, and include those sub-headers in the required <> headers.
The GCC team, for example, is working to minimize the amount of inclusions to speed up compile time.
OK, late answer, but I'll add this anyway.
It's about the <iostream> header. In C++98 and C++03 the standard did not guarantee that it would include <istream> and <ostream>, which meant that you were not guaranteed to have available e.g. std::endl. And at least one compiler insisted on being formal about it (in spite of all the non-normative examples in the standard showing the intention)!
Well, I can't remember who pointed it out first, but it was discussed up, down and sideways in [comp.lang.c++]. Several times. And finally James Kanze, bless his soul (well he's not dead yet, in fact he's here on SO), put it to the committee, and it was fixed for C++0x.
So, there's now one header dependency that you can depend on.
Hallelujah!
But in the other direction, C++0x increases the confusion about which headers can put which names in the global namespace and the std namespace. Now any standard library header corresponding to a C library header can freely pollute the global namespace, and be conforming. And so now there's no point in including, say, <cstdio>, but instead now the wise thing to do is to include <stdio.h> and accept a guaranteed global namespace pollution.
Cheers & hth.,
Yeah, you should not assume anything about inclusion of headers. I have been playing around with inclusion of headers for a while, and you know i observed that when it comes to header files like vector and string, you are 'almost' sure that you are including them from somewhere.
Yes but this things are good only when you are just playing around. I would suggest you to always include the headers.
There is no guarantee, but since <algorithm> uses pair internally it is common sense that it should include it. There are ways to make sure that a header file is included only once:
#pragma once http://en.wikipedia.org/wiki/Pragma_once
#ifndef MY_H
#define MY_H
//header code
#endif /* MY_H */
And usually a good library will include all the needed files to compile, and those will be using this kind of mechanism to make sure that they are included only once.
There are sometimes exceptions to this rule especially in private (personal, not standard) libraries where the included header files are placed in the order needed for them to compile. And in that case if you have three includes, probably the second include uses the code from the first and the third from the first and second.
Best approach is to include all that you need to have direct access to the data structures you use.
Related
Consider this code:
#include <vector>
struct S { };
int main()
{
std::vector<int> v;
// Do whatever work I need to with v
// Oh, by the way, I also need std::allocator for something else...
std::allocator<S> a;
S s;
a.construct(&s, S());
a.destroy(&s);
}
std::allocator is declared in <memory>, but I have not included that header.
Questions:
Can I still rely on std::allocator being fully usable through the inclusion of <vector>? Why/why not?
If so, what other classes can I rely on being included indirectly, and under what conditions?
(Is there a list somewhere, or would I have to figure them out manually?)
Is it good practice to avoid including the specific header (e.g. <memory>) if you've already included another header that implies the inclusion of the class you need? Why/why not?
The C++ standard allows any standard header to include an arbitrary number of other standard headers. It's almost never, however, actually required.
Just for example, it's fairly common to put implementation details in a detail namespace, and then pull names from there to become publicly accessible if and only if the user has included a header that needs to make them visible.
In other words, if you're using something, include the header. This is actually a pretty common source of problems. With older compilers, including one header often ended up defining a lot that that header wasn't required to define. Newer compilers tend to be more granular, so a lot of older code needs minor patching to include the proper headers before it'll work correctly. While not exactly the biggest portability problem that arises, this is sufficiently annoying that it's clearly better to avoid it when/if you can.
Even in the few places there's a documented requirement for one header to include another (or at least do the equivalent), I think it's a fairly poor idea to depend on it. First, because the #include lines act as a sort of documentation, and depending on indirect inclusion means anybody using them as documentation has to take all that indirection definition into account. Second, because it's easy to slip into thinking that because including one header has to define a few specific items normally defined in another header that it will automatically define everything in that header, which isn't necessarily true.
Either the standard provides a guarantee or it does not. If it does not, then you have no guarantee. Your "implies the inclusion" argument fails because the compiler is not required to include any more of the class that it needs, and clearly anything you do with the class specifically is more than is needed.
I am confused of which standard library include which other once. I heard that iostream includes ostream or something like that. Unfortunately I couldn't find an overview. That's why I ask now.
My program uses the following libraries: string, fstream, iostream, sstream, streambuf. Because they provide related functionality I wonder if any of these includes another of them already. In this case I could get rid of the redundant includes.
Is there a overview out there indicating which standard library includes which? or
Which of the libraries user by my program are redundant?
C++ provides no guarantees in general for any sort of recursive inclusion. It is your responsibility to always include all headers that you need. Similarly, it does not guarantee that any particular standard library header is not included. (For example, your implementation could legally always include all standard library headers!) That's why-and-because everything is in the std namespace.
(I believe there's a special provision for the C library headers - I think you won't get names in the global namespace unless you explicitly include those headers.)
Some headers do have specific requirements; for example, in C++11 (but not before) it is required that <iostream> include both <ostream> and <istream>. But that's just one specific case.
You can't rely on any headers being included by any other headers. It's best to explicitly include everything you need. That way, if you change the compiler, you can be sure not to break compilation, in case the new compiler doesn't have the same header include structure.
This may help: http://www.cplusplus.com/reference/iostream/iostream/ iostream is inherited from ostream and istream.
My rule: #include what you are using. If you are using std::string, you need to #include <string>. If you are using std::cout, you need to #include <iostream>. If you are using a file stream, #include <fstream>. And so on.
That you might get std::string for "free" from some of those other system headers that you include is irrelevant. Don't depend on those behind the scenes includes.
If you are worried of retundant includes they are handled via macros like
#ifndef MACRO_NAME
#define MACRO_NAME
#endif
So you dont need to worry about multiple includes i guess.
Just out of curiosity I wanted to know if is there a way to achieve this.
In C++ we learn that we should avoid using macros. But when we use include guards, we do use at least one macro. So I was wondering if there is a way to write a macro-free program.
It's definitely possible, though it's unimaginably bad practice not to have include guards. It's important to understand what the #include statement actually does: the contents of another file are pasted directly into your source file before it's compiled. An include guard prevents the same code from being pasted again.
Including a file only causes an error if it would be incorrect to type the contents of that file at the position you included it. As an example, you can declare (note: declare, not define) the same function (or class) multiple times in a single compilation unit. If your header file consists only of declarations, you don't need to specify an include guard.
IncludedFile.h
class SomeClassSomewhere;
void SomeExternalFunction(int x, char y);
Main.cpp
#include "IncludedFile.h"
#include "IncludedFile.h"
#include "IncludedFile.h"
int main(int argc, char **argv)
{
return 0;
}
While declaring a function (or class) multiple times is fine, it isn't okay to define the same function (or class) more than once. If there are two or more definitions for a function, the linker doesn't know which one to choose and gives up with a "multiply defined symbols" error.
In C++, it's very common for header files to include class definitions. An include guard prevents the #included file from being pasted into your source file a second time, which means your definitions will only appear once in the compiled code, and the linker won't be confused.
Rather than trying to figure out when you need to use them and when you don't, just always use include guards. Avoiding macros most of the time is a good idea; this is one situation where they aren't evil, and using them here isn't dangerous.
It is definitely doable and I have used some early C++ libraries which followed an already misguided approach from C which essentially required the user of a header to include certain other headers before this. This is based on thoroughly understanding what creates a dependency on what else and to use declarations rather than definitions wherever possible:
Declarations can be repeated multiple times although they are obviously required to be consistent and some entities can't be declared (e.g. enum can only be defined; in C++ 2011 it is possible to also declare enums).
Definitions can't be repeated but are only needed when the definition if really used. For example, using a pointer or a reference to a class doesn't need its definition but only its declaration.
The approach to writing headers would, thus, essentially consist of trying to avoid definitions as much as possible and only use declaration as far as possible: these can be repeated in a header file or corresponding headers can even be included multiple times. The primary need for definitions comes in when you need to derive from a base class: this can't be avoided and essentially means that the user would have to include the header for the base class before using any of the derived classes. The same is true for members defined directly in the class but using the pimpl-idiom the need for member definitions can be pushed to the implementation file.
Although there are a few advantages to this approach it also has a few severe drawbacks. The primary advantage is that it kind of enforces a very thorough separation and dependency management. On the other hand, overly aggressive separation e.g. using the pimpl-idiom for everything also has a negative performance impact. The biggest drawback is that a lot the implementation details are implicitly visible to the user of a header because the respective headers this one depends on need to be included first explicitly. At least, the compiler enforces that you get the order of include files right.
From a usability and dependency point of view I think there is a general consensus that headers are best self-contained and that the use of include guards is the lesser evil.
It is possible to do so if you ensure the same header file is not being included in the same translation unit multiple times.
Also, you could use:
#pragma once
if portability is not your concern.
However, you should avoid using #pragma once over Include Guards because:
It is not standard & hence non portable.
It is less intuitive and not all users might know of it.
It provides no big advantage over the classic and very well known Include Guards.
In short, yes, even without pragmas. Only if you can guarantee that every header file is included only once. However, given how code tends to grow, it becomes increasingly difficult to honour that guarantee as the number of header files increase. This is why not using header guards is considered bad practice.
Pre-processor macros are frowned upon, yes. However, header include guards are a necessary evil because the alternative is so much worse (#pragma once will only work if your compiler supports it, so you lose portability)
With regard to pre-processor macros, use this rule:
If you can come up with an elegant solution that does not involve a macro, then avoid them.
Does the non-portable, non-standard
#pragma once
work sufficiently well for you? Personally, I'd rather use macros for preventing reinclusion, but that's your decision.
Is it reasonable to put custom headers higher in include section than standard headers?
For example include section in someclass.hpp:
#include "someclass.h"
#include "global.h"
#include <iostream>
#include <string>
Is it best practice? What is the profit if it is?
The reason is that if you forget to include a dependent header in someclass.h, then whatever implementation file includes it as the first header, will get a warning/error of undefined or undeclared type, and whatnot. If you include other headers first, then you could be masking that fact - supposing the included headers define the required types, functions, etc. Example:
my_type.h:
// Supressed include guards, etc
typedef float my_type;
someclass.h:
// Supressed include guards, etc
class SomeClass {
public:
my_type value;
};
someclass.cpp:
#include "my_type.h" // Contains definition for my_type.
#include "someclass.h" // Will compile because my_type is defined.
...
This will compile fine. But imagine you want to use use SomeClass in your program. If you don't include my_type.h before including someclass.h, you'll get a compiler error saying my_type is undefined. Example:
#include "someclass.h"
int main() {
SomeClass obj;
obj.value = 1.0;
}
It is fairly common practice to #include "widget.h" as the first thing in widget.cpp. What this does is ensure that widget.h is self-contained, i.e. does not inadvertently depend on other header files.
Beyond that, I think it's essentially a matter of personal preference.
There are two important observations to be made before delving in the specifics:
When you develop a new header/source pair, it is important to check that the header is self-contained. To do so, the easiest way is to include first in a file.
It is best not to include extraneous things before including a header you do not own, as this could create strange issues in case of conflict of macros or overload of functions.
Therefore, the answer depend if you have unit test or not.
A general rule of thumb is to include headers starting with the Standard Library, then 3rd party headers (including Open Source projects), then your own middleware, utilities, etc... and finally the headers local to this library. It more or less follows the order of dependencies to comply with observation 2.
The only exception I have seen was the one header corresponding to the current source file, which would be included first to make sure it is self-contained (observation 1)... but this only holds if you don't have unit tests, for if you do then the unit test source file is a very good place to check this.
While it is just personal choice, I would prefer to include standard headers first. Few reasons:
Any set of #ifdef..#define would be correctly mapped, rather than standard headers misinterpreting them. This goes for conditional compilation as well as values of some macros, while standard headers are being compiled.
Any change/new function in standard header may conflict with your function, and compiler would emit error in header file, which would be be complicated to solve.
All required standard headers should be placed in one header (preferbly some pre-compiled-header), include that header, and then include your custom header. This would reduce compilation time.
Start with the system headers.
If there are no dependencies between the headers both ways work, but since programming is essentially communication, not with the computer but with other humans, it is important to make it logical and easy to understand. And my opinion is that it is better to start with the system headers.
I base this one of my very first programming courses (in 1984, I think), where we programmed in Lisp and were taught to think like this: you start with the normal Lisp language, and then you create a new language that is more useful for your application by adding some functions and data types. If you for example add dates and the ability to manipulate dates, this new language could be called Lisp-with-dates. Then you could use Lisp-with-dates to create a new language with calendar functionality, which could be called Lisp-with-calendars. Like layers in an onion.
Similarly, you can view C as having a "core" language, without any headers, and then you can for example expand this language into a new, bigger language with I/O functionality by #including stdio.h. You add more and more stuff to the core language by #including more headers. (I am aware that the term "C language" in other contexts refers to the entire standard, with all the standard headers, but bear with me here.) Each new #included header creates a new, bigger language, and an additional layer of the onion.
Now, to me it seems that the standard headers obviously should be the inner part of this onion, and therefore before the custom headers. You can create the language C-with-monsters by adding stuff to C-with-I/O, but the people who created C-with-I/O did not start with C-with-monsters.
any place you include c++ compiler treats it as the same
I know why include guards exist, and that #pragma once is not standard and thus not supported by all compilers etc.
My question is of a different kind:
Is there any sensible reason to ever not have them? I've yet to come across a situation where theoretically, there would be any benefit of not providing include guards in a file that is meant to be included somewhere else. Does anyone have an example where there is an actual benefit of not having them?
The reason I ask - to me they seem pretty redundant, as you always use them, and that the behaviour of #pragma once could as well just be automatically applied to literally everything.
I've seen headers that generate code depending on macros defined before their inclusion. In this case it's sometimes wanted to define those macros to one (set of) value(s), include the header, redefine the macros, and include again.
Everybody who sees such agrees that it's ugly and best avoided, but sometimes (like if the code in said headers is generated by some other means) it's the lesser evil to do that.
Other than that, I can't think of a reason.
#sbi already talked about code generation, so let me give an example.
Say that you have an enumeration of a lot of items, and that you would like to generate a bunch of functions for each of its elements...
One solution is to use this multiple inclusion trick.
// myenumeration.td
MY_ENUMERATION_META_FUNCTION(Item1)
MY_ENUMERATION_META_FUNCTION(Item2)
MY_ENUMERATION_META_FUNCTION(Item3)
MY_ENUMERATION_META_FUNCTION(Item4)
MY_ENUMERATION_META_FUNCTION(Item5)
Then people just use it like so:
#define MY_ENUMERATION_META_FUNCTION(Item_) \
case Item_: return #Item_;
char const* print(MyEnum i)
{
switch(i) {
#include "myenumeration.td"
}
__unreachable__("print");
return 0; // to shut up gcc
}
#undef MY_ENUMERATION_META_FUNCTION
Whether this is nice or hackish is up to you, but clearly it is useful not to have to crawl through all the utilities functions each time a new value is added to the enum.
<cassert>
<assert.h>
"The assert macro is redefined according to the current state of NDEBUG each time that
<assert.h> is included."
It can be a problem if you have two headers in a project which use the same include guard, e.g. if you have two third party libraries, and they both have a header which uses an include guard symbol such as __CONSTANTS_H__, then you won't be able to successfully #include both headers in a given compilation unit. A better solution is #pragma once, but some older compilers do not support this.
Suppose you have a third party library, and you can't modify its code. Now suppose including files from this library generates compiler warnings. You would normally want to compile your own code at high warning levels, but doing so would generate a large set of warnings from using the library. You could write warning disabler/enabler headers that you could then wrap around the third party library, and they should be able to be included multiple times.
Another more sophisticated kind of use is Boost's Preprocessor iteration construct:
http://www.boost.org/doc/libs/1_46_0/libs/preprocessor/doc/index.html
The problem with #pragma once, and the reason it is not part of the standard, is that it just doesn't always work everywhere. How does the compiler know if two files are the same file or not, if included from different paths?
Think about it, what happens if the compiler makes a mistake and fails to include a file that it should have included? What happens if it includes a file twice, that it shouldn't have? How would you fix that?
With include guards, the worst that can happen is that it takes a bit longer to compile.
Edit:
Check out this thread on comp.std.c++ "#pragma once in ISO standard yet?"
http://groups.google.com/group/comp.std.c++/browse_thread/thread/c527240043c8df92