I have two files, my_program.cpp and its header my_program.h.
my_program.cpp contains only this:
#include "my_program.h"
using namespace std;
my_program.h contains a pointer to a function which returns a wstring, as follows:
using namespace std;
typedef wstring (*my_function)(wstring, int, int, int, int);
The program doesn't compile in this state (stops at typedef... saying that ISO C++ forbids declaration of 'wstring' with no type) but if I add #include <iostream> before #include "my_program.h" in the .cpp file, the program miraculously compiles.
Why does this happen? I just hope I didn't make a foolish mistake and I'm now going to be laughed at.
You really should include <string>.
From the sound of things, your compiler's <iostream> happens to include <string>, so it works, but on a different compiler it may not. C++ allows a standard header to include other standard headers, but doesn't require it. In some cases, you get only a declaration of the class, so some things work, and others don't.
At least in my experience, this is also an issue that's likely to change from one version of a compiler to the next, so even if you don't intend to port to anything else, your code may quit working just due to a seemingly trivial upgrade unless you include the right header.
Before you add #include <iostream>, the compiler has no idea what wstring is -- hence the error
After you include the iostream header, (which defines std::wstring -- possibly via other headers it includes), the compiler knows what wstring refers to and can properly parse the typedef.
One thing to keep in mind is that the compiler only cares about what's called the compilation unit (.cpp files), not the headers; the headers come into play when a compilation unit includes them (think of verbatim copy-paste). Therefore you can include iostream (or as others pointed out <string>) anywhere before the typedef, to make it work -- from this perspective, including it before the header counts the same as including it at the first line of the header.
It is generally a good idea, however, to make headers as self consistent as possible (so in your case include the relevant headers in your header, instead of the .cpp), so the includers do not need to remember what other headers to include as well to make it work as intended.
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 a newbie in c++, and I suspect, that, of course the question relates not only to tuple.
So, I've watched a tutorial with roughly this code:
#include <tuple>
std::tuple<...> t(...)
Why #include <tuple>? Especially, given the fact that we explicitly write std::tuple. The code compiles without that #include line just well...
Because <tuple> is a header file which contains the tuple class inside the namespace std. Just because you're explicitliy saying std:: doesn't mean the compiler will just be able to find it if it's not included.
The reason it worked for you in this case is probably because another header you have included already includes <tuple> and thus your code includes <tuple> indirectly or because the compiler you're building with includes it automatically. This is not guaranteed by the standard and should not be relied upon. Always include the headers you'll need to make your code portable.
You always should include the specific headers for any types that you use in your code.
The code compiles without that #include line just well...
That your code compiles without is just by chance, because it might have been included by another standard header you use in your program, and not guaranteed by the standard, and thus not portable.
Especially, given the fact that we explicitly write std::tuple.
The explicit use of the std:: namespace doesn't have any significance about that rule.
You should also always be explicit about using classes or types from the std namespace to prevent getting into ambiguity troubles.
Related stuff:
Why is “using namespace std;” considered bad practice?
Why should I not #include ?
How do I include the string header?
In C++ you need to include the header for everything you use. The std:: is about the namespace, it's completely different.
Apparently your compiler is smart enough to deal with it, but most of the compilers won't.
Some standard headers shall include other standard headers according to the C++ Standard. For example the header <algorithm> must include the header <initializer_list>.
However implementations are allowed to include standard headers in other standard headers at their discretion.
You should not rely on this because your program compiled with one compiler will not compile using another compiler.
Even if one standard header is included in another standard header according to the requirements of the C++ Standard nevertheless it is a good practice to include such a header explicitly because the user of the program (some other programmer) should bother about dependencies of the headers and will be free to include or exclude other headers.
Our C++ library contains a file with a namethat is (considered) equal to one of the standard libraries' headers. In our case this is "String.h", which Windows considers to be the same as "string.h", but for the sake of this question it could be any other ile name used in the standard library.
Normally, this file name ambiguity is not a problem since a user is supposed to set up the include paths to only include the parent of the library folder (therefore requiring to include "LibraryFolder/String.h") and not the folder containing the header.
However, sometimes users get this wrong and directly set the include path to the containing folder. This means that "String.h" will be included in place of "string.h" in both the user code and in the standard library headers, resulting in a lot of compile errors that may not be easy to resolve or understand for beginners.
Is it possible, during compile-time, to detect such wrongly set up include paths in our libraries' header and throw a compile #warning or #error right away via directive, based on some sort of check on how the inclusion path was?
There's no failsafe way. If the compiler finds another file, it won't complain.
However, you could make it so you can detect it. In your own LibraryName/string.h, you could define a unique symbol, like
#define MY_STRING_H412a55af_7643_4bd6_be5c_4315d3a1e6b7
Then later in dependent code you could check
#ifndef MY_STRING_H412a55af_7643_4bd6_be5c_4315d3a1e6b7
#error "Custom standard library path not configured correctly"
#endif
Likewise you could use this to detect when the wrong version of the library was included.
[edit - as per comments]
Header inclusion can be summarized as :
Parse #include line to determine header name to look up
Depending on <Foo.h> or "Foo.h" form, determine set of locations (usually directories) to search
Interpret the header name, in an implementation-dependent way. (usually as a relative path). Note that this is not necessarily as a string, e.g. MSVC doesn't treat \ as a string escape character.
If the header is found (usually, if a file is found), replace the #include line with the content of that file. If not, fail the compilation.
(The parenthesized "usually" apply to MSVC, GCC, clang, etc but theoretically a compiler could compile directly from a git repository instead of disk files)
The problem here is that the test imagined (spelling of header name) must be located in the included header file. This test would necessarily be part of the replaced #include line, which therefore no longer exists and cannot be tested.
C++17 introduces __has_include but this does not affect the analysis: It would still have to occur in the included header file, and would not have the character sequence from the #include "Foo.h" available.
[old]
Probably the easiest way, especially for beginners is to have a LibraryName/LibraryName.h. Hopefully that name is unique.
The benefit is that once that works, users can replace #include "LibraryName.h" with just #include "String.h" as you know the path is right.
That said, "String.h" is asking for problems. Windows isn't case sensitive.
Use namespaces. In your case this would translate into something like this:
MyString/String.h
namespace my_namespace {
class string {
...
}
}
Now to make sure your std::string or any other class named string is not accidentally used instead of my_namespace::string (by any means, including but not limited to setting up your include paths incorrectly) you need to refer to your type using its fully qualified name, namely my_namespace::string. By doing this you avoid any naming clashes and are guaranteed to get a compile error if you don't include the correct header file (unless there's actually exists another class called my_namespace::string that is not yours). There are other ways to avoid these clashes (such as using my_namespace::string) but I'd rather be explicit about the types I'm using. This solution is costly however because it probably needs change all over your code base (changing all strings to my_namespace::string).
A somewhat less cumbersome alternative would be to change the name of the header String.h to something like MyString.h. This would quickly introduce compile errors but requires changing all your includes from #include "String.h" into#include "MyString.h"` (Should be much less effort compared to the first option).
I cannot think of any other way that requires less effort as of now. Since you were looking for a solution that would work in all similar scenarios I'd go with the namespaces if I were you and solve the problem once and for all. This would prevent any other existing/future naming clashes that may be in you code.
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.
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.