I have two questions:
to use compare function, I need to include <string>but I don't need to include <cctype> to use isdigit, ispunct etc?
what's the difference between <cctype> and ctype.h? why there is only <string> not string.h?
Always include the headers for everything you use in a file. If you use functionality from A and B, include A and B even if A includes B because tomorrow A might not include B. Why put up with that debugging nightmare if you don't have to? Every file should be self consistent.
This is also true of system headers. There is no assurance that string or any header includes anything. One implementation could include everything down to the kitchen sink and the next implementation, or a different version of the same implementation, could forward-declare what it needs and carry on. Do not assume any chain of includes in any code you do not control.
The c* headers primarily wrap the *.h headers from the C standard library. This places C++-ized versions in the std namespace and takes care of name mangling for you. Often the C++-ized versions have type safety tweaks or are templates that call the C version.
Related
I am reading from here : Can std::string be used without #include <string>?, <iostream> is calling <string>. But I do not see any includes of <string> in Standard library header <iostream> from c++ standard: https://en.cppreference.com/w/cpp/header/iostream. In <iostream> is only included <ios>, <streambuf>, <istream> and <ostream> according to that documentation. So this code works (file foo.cpp):
#include <iostream>
int main(){
std::cout << "enter srting\n";
std::string out; //std::string should not be included according to standard documentation
std::cin >> out;
std::cout << "test, " << out;
}
But I have to try to see dependecies generated from gcc:
cc -H foo.cpp |& vim -
and the output is (I have regex out files with string in it):
. /usr/include/c++/8/iostream
..... /usr/include/c++/8/bits/stringfwd.h
...... /usr/include/c++/8/string
....... /usr/include/c++/8/bits/basic_string.h
........ /usr/include/c++/8/ext/string_conversions.h
....... /usr/include/c++/8/bits/basic_string.tcc
So I can see that in the end, many "string" headers are indeed included
(so should I trust that documentation, when the did not mentioned <string> header in "Includes" list of <iostream>?).
Some of them are deeper on the #include stack (term from gcc manual), which brings me to question,
what calls what? And what is the "true" header, that define std::string of them? (is it /usr/include/c++/8/bits/basic_string.h?...)
from this question Why does omission of "#include <string>" only sometimes cause compilation failures?, they mentioned:
Some compilers on some platforms may on some time of the month compile even though you failed to include the header
But from the upper output of the "string headers", there is multiple of them , so how's possible for a compiler to compile only sometimes? Which of these headers are really important for successful compilation?
How to orient in cpp headers, which are meaningful for compiler, and could be tracked their "#include stack" (i.e. other meaningful headers)?
EDIT:
If it depends on my specific implementation of my stdlib++, then I want to know how can I determine from source whether that inclusion is made before I try to compile. Not by "If it compiles, then it works".
In general you cannot know what headers are transitively included by the headers you include, and any standard header is allowed to, but not required to, include any other header. And you shouldn't rely on transitive includes ever. You should include the headers you need for the things that you use and then you'll be good.
You should always check the documentation for any symbol you use and include any headers it is specified to require.
The C++ standard only specifies which symbols must be made available when a standard header is included. It does not place any limits on what other symbols are made available. In your example, the standard specifies the <iostream> must include <ios>, <streambuf>, <istream>, and <ostream>, but <iostream> may include any other headers its authors want. It may also forward-declare any symbols it may need.
(so should I trust that documentation, when the did not mentioned <string> header in "Includes" list of <iostream>?).
You should trust that the symbols specified as being available when you include <string> will be. That is all. You may not assume that those symbols will not be visible when including any other header.
what calls what? And what is the "true" header, that define std::string of them? (is it /usr/include/c++/8/bits/basic_string.h?...)
This is an implementation detail that can only be answered by inspecting the implementation's headers. Libstdc++ (the standard library implementation used by GCC) has the declaration of the std::string class in bit/stringfwd.h and its definition in bits/basic_string.h and bits/basic_string.tcc (for the current version, at least), but that is not required at all. If the libstdc++ maintainers decided they wanted to refactor and reorganize things, they would be free to do so. The only requirement that is guaranteed by the C++ language is that std::string must be available when <string> is included.
But from the upper output of the "string headers", there is multiple of them, so how's possible for a compiler to compile only sometimes?
Different standard library implementations or different versions of the same implementation could transitively include different headers. Different compiler flags (i.e. a debug flag or different standard compliance mode) could transitively include different headers.
Which of these headers are really important for successful compilation?
How to orient in cpp headers, which are meaningful for compiler, and could be tracked their "#include stack" (i.e. other meaningful headers)?
All of them are meaningful. The standard library's authors wouldn't include a header if they didn't need it for something. Just because you aren't using any symbols declared/defined in that header directly doesn't mean none are being used.
EDIT: If it depends on my specific implementation of my stdlib++, then I want to know how can I determine from source whether that inclusion is made before I try to compile. Not by "If it compiles, then it works".
The only way to know is to look at your standard library implementation's headers. There is nothing magical about them; they're just C++ code. If you want to know if <iostream> includes a declaration or definition of std::string, open your implementation's copy of <iostream> and look for a declaration or definition of std::string. Repeat this process for any headers that <iostream> includes.
<iostream> is calling <string>
Do you mean that it includes <string>? Calling is something that is done to functions.
But I do not see any includes of <string> in Standard library header <iostream> from c++ standard: https://en.cppreference.com/w/cpp/header/iostream.
What you're reading is documentation of <iostream>. Indeed, <iostream> is not documented to include <string>.
So this code works (file foo.cpp):
It may work with some standard library implementation. It may not work using other implementations.
(so should I trust that documentation, when the did not mentioned <string> header in "Includes" list of <iostream>?).
cppreference is fairly high quality. Unless it contradicts the standard, it is fairly safe to assume that it is correct. Indeed in this regard it is correct: <iostream> is not guaranteed to include <string>.
what calls what?
Some headers include some other headers. There is no need to know more accurately than that because you should not rely on transitive inclusions (except those that are documented).
And what is the "true" header, that define std::string of them?
As per documentation, std::string is defined in header named string (commonly stylised as <string> which matches the conventional inclusion syntax).
so how's possible for a compiler to compile only sometimes?
It could ask the current time from the operating system and use a branch to do one thing or another depending on that time. Compilers don't typically do that, but the point is that they could.
More realistically, you may at some point need to compile your program using another (version) of the compiler (or standard library implementation). Different implementations behave different from one another.
Which of these headers are really important for successful compilation?
The ones that are documented to define and declare the names whose definitions and declarations your program relies on. If you use std::string, then you must include the header that defines std::string which is <string>.
I am used to writing codes using stl pair without including any specific header file for using pair. But a friend today told me that I should use utility header whenever I use pair else I will have problem on some compilers. Please tell if this is true. And what is the use of utility header if I can write codes without using it.
You should almost always include header file for every class which you use in your program, otherwise you depend on the fact that some headers internally use a class of your interest, but this can change on another compiler or version. You need to read reference of a class (for example on cppreference.com - http://en.cppreference.com/w/cpp/utility/pair ) and check which header file you need to include - in case of std::pair you should add #include <utility> . You cannot depend on the fact, that, for example, iostream already includes iomanip and your code compiles when you use manipulators like setw etc. You cannot - you always should refer to language specs and include required headers.
The point is that you may have had indirectly included the <utility> header through the inclusion of some other header. Usually it is the case that headers are included by other headers in a C++ implementation without that inclusion being mandated by the standard. So, by including <utility>, you make sure your code is portable across standard compliant implementations (at least with respect to this particular issue).
The standard specifies that std::pair is in <utility>, so you should include this whenever you use an std::pair.
You always need to include the headers defining the components you use. Some standard libraries will be implemented to include other declarations they use internally butyou can't rely on this, at all. I consider it an error that standard libraries make declarations available they are not required to make available.
The class template std::pair is made available by <utility>.
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.
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
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.