This question already has answers here:
Should I include every header?
(2 answers)
Closed 7 years ago.
consider this translation unit:
#include <map>
#include <string>
int main()
{
std::map<std::string, std::size_t> mp;
mp.insert(std::make_pair("hello", 42));
}
There are two things in this translation unit that are bothering me, and they are
std::size_t
std::make_pair
I have just assumed that <cstddef> and <utility> must have been #included by <string> and <map>.
How rightful is this assumption? At least for make_pair I think there's a pretty strong guarantee because map member interfaces use std::pair. For std::size_t there is no formal guarantee but still it is very very very likely that it is available as soon as you include map or string. The stylistic question number one is Would you explicitly include <cstddef> and <utility> in this translation unit?
This part partly deals with the uncertaintly of some header being already included. However, there's the second part of the question. Suppose we have this
//f.h
#ifndef BIG_F_GUARD
#define BIG_F_GUARD
#include <string>
std::string f();
#endif
//f.cpp
#include "f.h"
std::string f()
{
std::string s;
return s;
}
Second question is: Would you explicitly #include <string> into f.cpp?
I think I made my question clear. Btw. both questions are followed by a big WHY :) Thanks.
In the first case, I probably wouldn't but I should, if I want my code to be properly portable. There's no requirement that map::size_type is size_t, so there's no necessity for <map> to include a definition of size_t. For that matter, size_t can be a type alias rather than a distinct type, so even if size_type is size_t, it needn't have been defined in <map> using that name. So as you say, it's likely but not guaranteed that <map> includes <cstddef>.
In the second case, I definitely wouldn't, because I know I don't need to. IMO a .cpp file is entitled to rely on the headers included by its corresponding .h file, since you kind of expect that if you modify the .h file you potentially need to modify the .cpp file too -- change an interface implies change its implementation, most of the time. And even if you feel I'm not entitled, I can always document that f.h includes <string>, in which case I can rely on that.
Regarding <utility>, I don't know whether <map> is allowed to define std::pair (because it needs it) without defining std::make_pair (which is from the same standard header, and for the sake of argument let's say it isn't needed to define <map>). This would be possible if the implementation's version of <utility> itself includes a bunch of other files, for different bits, and <map> just includes the bit it needs. Specific permission is given for headers to include other headers, but I don't know whether specific permission is given for headers to put things in namespace std without including the whole of the corresponding header. The thing is, in practice it is very difficult to notice that you've forgotten a standard include in these cases, because implementations don't check for you, and that's why I know that in practice I'd quite likely not do it. Luckily it should be any easy fix for anyone porting to an implementation with different header dependencies.
What I tend to do, and it's not necessarily the right thing to do, is to include all the files I need to get the module to compile. The only problem with this is that when dependencies change, you can end up with code included which isn't necessarily used. However a good compiler will normally deal with this.
There's no need to include <string> in your .cpp file however, because it's included through the header file. The contents of any included header files essentially get 'pasted' into your cpp file.
Hope this helps!
No (as long as it's something you know it has to be in there on all platforms targeted; e.g. size_t due to it being one of the parameter/return types of string stuff)
No (as the header file is your under your control and you know it's already included)
To answer your questions:
No
No
Include minimal stuff to make it compile, but no obsolete/additional dependencies that are already fulfilled
Atleast <map> is forced to include <utility> because the template for map looks like this:
namespace std {
template <class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T> > >
class map;
}
(Standard 23.3/1)
My two bits:
main.cpp: I would #include <cstddef> but probably not <utility> here. You are using std::size_t independent of whether it happens to be defined in the standard library headers. On the other hand, read the documentation on std::map and it is very clear that <map> must somehow define std::pair. There's no reason to #include <utility>. (This is particularly so since the connection between std::pair and is a bit of a WTF without reading the fine documentation.)
f.hh: I would grudingly #include <string> here. Normally it is better to forward declare a class rather than #include the header that defines the class if the class is only used as a reference, a pointer, or a return type. The only reason to #include <string> in f.hh is because forward declaring std::string is a bit tough.
f.cpp: I would #include <string> here. If the return type from f() was some class Foo rather than std::string, the expectation should be that the header merely forward declares Foo. The source file needs to #include the header that specifies class Foo. That the return type is std::string doesn't change this basic concept. Who knows? Some pedantically correct programmer might fix the problem in f.hh. (The problem with f.hh being that it #includes <string> when it doesn't really need to do so.)
Related
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.
Suppose I have a class called CameraVision in the file CameraVision.cpp.
The constructor for this class takes in a vector of IplImage* (IplImage is a C struct that represents an image in OpenCV). I need to #include opencv.h either in CameraVision.hpp or CameraVision.cpp.
Which is better and why? (#including these in CameraVision.hpp or in CameraVision.cpp?)
Also, where should I #include STL <vector>, <iostream>, etc. ?
Suppose the client of CameraVision.cpp also uses <vector> and <iostream>. The client would obviously #include CameraVision.hpp (since he is a client of CameraVision). Should the client of CameraVision.cpp also #include , <iostream>, etc. if they have already been #include'd in CameraVision.hpp? How would the client know this?
The rule here is: Limit scope. If you can get away with having the include in the implementation file only (e.g. by using a forward declaration, including <iosfwd> etc.), then do so. In public interfaces, i.e. the headers that your clients will include to use a library of your making, consider using the PIMPL pattern to hide any implementation details.
The benefits:
1) Clarity of code. Basically, when somebody is looking at a header file, he is looking for some idea of what your class is about. Every header included adds "scope" to your header: Other headers to consider, more identifiers, more constructs. In really bad code, every header includes yet more headers, and you cannot really understand one class without understanding the whole library. Trying to keep such dependencies at a minimum makes it easier to understand the interface of a class in isolation. ("Don't bother what IplImage actually is, internally, or what it can do - at this point all we need is a pointer to it").
2) Compile times. Since the compiler has to do the same kind of lookup as described in 1), the more includes you have in header files, the longer it takes to compile your source. In the extreme, the compiler has to include all header files for every single translation unit. While the resulting compile time might be acceptable for a once-over compilation, it also means that it has to be re-done after any change to a header. In a tight edit - compile - test - edit cycle, this can quickly add up to unacceptable levels.
Edit: Not exactly on-topic, but while we're at it, please don't use using in header files, because it's the opposite of limiting scope...
To avoid extra includings, you should use #include in implementation (.cpp) files in all cases, except in situations when names that you are importing, used in prototypes or declarations, which your module exports.
For example:
foo.h:
#ifndef _FOOBAR_H_
#define _FOOBAR_H_
#include <vector>
void foo();
std::vector<int> bar();
#endif // _FOOBAR_H_
foo.cpp:
#include "foo.h"
#include <iostream>
void foo() {
std::cout << "Foo";
}
std::vector<int> bar() {
int b[3] = {1, 2, 3};
return std::vector<int>(b, b+3);
}
If a type is used/referenced only within the implementation file, and not in the header file, you should #include only in the implementation file, upholding the principle of limited scope.
However, if your header file references a type, then your header file should #include that type's header file. The reason being that your header file should be able to be completely understood and have everything it needs when it is #included.
One justification for this perspective is not just for building/compiling, but also tooling. Your development environment may parse header files to provide you with type assistance (e.g. Intellisense, Command Completion, etc...) which may require complete type information to work properly.
Another justification is if your header file is used by another party, that that party has enough information about your types to make use of your code. And they should not have to #include several files to get one type to compile.
You should not #include a type's header file in another type's header file simply to avoid having to #include two files in the implementation file. Instead, a third header file should be made for the purpose of aggregating those types.
I'm using a custom library in a c++ project, witch includes several std headers, but when i include the corresponding header in the main file, it's like i included all the headers in the custom one.
To be clear:
custom header file:
#ifndef CUSTOM_H
#define CUSTOM_H
#include <vector>
//stuff
#endif
Main.cpp:
#include <iostream>
#include "custom.h"
//here, let suppose that i do next:
vector<int> vec;
return 0;
there's no compile error, like the vector header is included, i want to avoid that, any suggestion
If custom.h's use of std::vector is an implementation detail (and not exposed in the signatures of things you define in the header), consider moving the #include <vector> to the corresponding custom.cpp file instead.
If you can't move the include out of custom.h because, say, you pass a vector in or out of a method, then it truly is part of your interface and clients of your header will need to know about it.
It is possible, but this shouldn't be done without consideration because it gives meaning to the order in which you include files, that is, you will or won't be able to compile depending on what order your #includes are in. It is generally desirable to avoid that situation.
To accomplish that, remove #include <vector> from the .h and add it to Main.cpp above where you include the custom header file. If you #include it below that, it will complain about types being undefined. Also in every file that uses the custom header file, they will have to #include <vector> first.
The problem is nearly unavoidable. If your header file needs to include another for any reason whatsoever, there's no way to "uninclude" it later.
There's one technique that can minimize the problem, the pimpl idiom or opaque pointer. By moving the implementation of a class into a private source file, you eliminate the dependencies that caused you to include the header in the first place.
I'm porting some open source code so that it can build on another c++ compiler. One of the difficulties and themes that seem to keep cropping up are implementation differences of the provided standard library by the compiler.
For example, one of the source files that I'm compiling includes <sys/types.h>. However, it gives me the following errors:
Error E2316 g:\Borland\BCC593\Include\sys/types.h 45: 'time_t' is not a member of 'std'
Error E2272 g:\Borland\BCC593\Include\sys/types.h 45: Identifier expected
After looking at the root cause of this I found that one of the main include headers of the project is including <sys/types.h> in this pattern:
project_source1.cpp:
#include "../TargetPlatform.h"
#include "project_config.h"
#include <windows.h>
namespace project_namespace {
#include "project_component/all.h"
// more project includes down here
// ...
}
project_component/all.h:
#ifndef INCLUDE_GUARDS
#define INCLUDE_GUARDS
#include <sys/types.h>
#include "project_header1.h"
#include "project_header2.h"
// and other headers etc..
// followed with class definitions and what not.
#endif
This is all well and good except for one problem, the <sys/types.h> is implemented something like this for the compiler I'm porting to:
<sys/types.h> trimmed to the essence:
namespace std {
typedef long time_t;
typedef short dev_t;
typedef short ino_t;
typedef short mode_t;
typedef short nlink_t;
typedef int uid_t;
typedef int gid_t;
typedef long off_t;
} // std
using std::time_t;
using std::dev_t;
using std::ino_t;
using std::mode_t;
using std::nlink_t;
using std::uid_t;
using std::gid_t;
using std::off_t;
And this is the cause of the compile error I'm seeing. Because the project is including <sys/types.h> inside its own namespace, things like time_t, off_t, dev_t etc get put into the scope project_namespace::std:: which is obviously not what's intended.
What's the best way to handle this? Keep in mind there could be other standard library headers defined in a similar fashion and not just sys/types.h. Are there any C++ idioms that's relevant or semi-related to this issue(or possibly even at odds with it due to the way this is implemented)? If so, how can it be reconciled?
Thanks
This is a bad idea. Do not do things this way. Put the namespace declarations inside each header file. Never have a #include directive inside the scope of a namespace.
Never is a strong word, and there are very rare cases in which you might want to do this. If the file you're #includeing also has #include directives, you almost certainly do not want to be doing this, even more so than if they didn't.
If you need to be able to easily rename your namespace or use the same header to declare the same symbols in several different namespaces depending on context, use the preprocessor to change the namespace name instead. That's extremely ugly to do, but much better than what you're currently doing.
One thing you can do as a quick and dirty solution to this is #include <sys/types.h> and any other system header that's included before the namespace declaration. This will cause the double-inclusion guards in the system header files to kick in and avoid declaring stuff inside the namespace.
I would say you need to change the offending code so that the standard types are no longer defined within project_namespace.
It seems to me you have two major issues: [1] you have a catch-all header in project_all.h and [2] it's #included inside namespace project_namespace. I'll address the latter first. If your project has things it wants to put in its own namespace, that's fine, but it should be done as follows:
// Foo.h
// includes go here
namespace project_namespace {
class Foo { ... }
}
// Foo.cpp
// includes go here
namespace project_namespace {
// Foo implementation goes here
}
... in other words, your classes' header and implementation files need to say what namespace the classes belong in, "self-namespacing" as it were. All your #includes are outside a namespace because the header file for each class declares the namespaces the class belongs to. This is the convention used by the standard library.
Now if you still want to use a project_all.h you can do so. Without the namespace -- because each header file will place its declarations in the namespace it wants to (or not).
But it would be better to dispense with project_all.h; instead, #include the header files individually and make the dependencies explicit. And if the response is "there are too many header files", that's probably a sign of a high degree of coupling between your components.
I realize this is probably not the answer you wanted, sorry ...
I'm having a really nasty problem with some code that I've written. I found someone else that had the same problem on stackoverflow and I tried the solutions but none worked for me.
I typedef several common STL types that I'm using and none of the others have any problem except when I try to typedef a map.
I get a "some_file.h:83: error: expected initializer before '<' token" error when including my header in a test program.
Here's the important part of the header(some_file.h):
#ifndef SOME_FILE_H
#define SOME_FILE_H
// some syntax-correct enums+class prototypes
typedef std::string str;
typedef std::vector<Column> col_vec;
typedef col_vec::iterator col_vec_i;
typedef std::vector<Row> row_vec;
typedef row_vec::iterator row_vec_i;
typedef std::vector<str> str_vec;
typedef str_vec::iterator str_vec_i;
typedef std::vector<Object> obj_vec;
typedef obj_vec::iterator obj_vec_i;
typedef std::map<Column, Object> col_obj_map; // error occurs on this line
typedef std::pair<Column, Object> col_obj_pair;
The includes in some_file.cpp are:
#include <utility>
#include <map>
#include <vector>
#include <iostream>
#include <string>
#include <stdio.h>
#include <cc++/file.h>
#include "some_file.h"
The test file simply includes string, vector, and my file in that order. It has a main method that just does a hello world sort of thing.
The funny thing is that I quickly threw together a templated class to see where the problem was (replacing the "std::map<Column..." with "hello<Column...") and it worked without a problem.
I've already created the operator overload required by the map if you're using a class without a '<' operator.
You are getting this problem because the compiler doesn't know what a map is. It doesn't know because the map header hasn't been included yet. Your header uses the STL templates: string, vector, map, & pair. However, it doesn't define them, or have any reference to where they are defined. The reason your test file barfs on map and not on string or vector is that you include the string and vector headers before some_file.h so string and vector are defined, but map is not. If you include map's header, it will work, but then it may complain about pair (unless your particular STL implementation includes pair in map's header).
Generally, the best policy is to include the proper standard header for every type you use in your own header. So some_file.h should have, at least, these headers:
#include <string>
#include <map>
#include <utility> // header for pair
#include <vector>
The downside to this approach is that the preprocessor has to load each file every time and go through the #ifdef ... #endif conditional inclusion processing, so if you have thousands of files, and dozens of includes in each file, this could increase your compilation time significantly. However, on most projects, the added aggravation of having to manage the header inclusion manually is not worth the miniscule gain in compilation time.
That is why Scott Meyers' Effective STL book has "Always #include the proper headers" as item #48.
Is there a #include <map> somewhere in your header file?
Put that in there to at least see if it works. You should be doing that anyway.
You should shift some of those includes into your header file. These need to be placed before your typedef statements.
i.e.
#include <map>
#include <string>
#include <map>
Otherwise, anything else including some_file.h (such as your main program) won't know what they are unless it also places these includes before the #include "some_file.h" include directive in your main program source file. If you do this, the problem should go away.
As several people have pointed out, the compiler isn't finding the definition for map. Since you appear to be including the map header, there's 2 other possible causes i can think of:
Another header file called map is being loaded instead of the std map header. I think this is unlikely.
Another header is #define'ing map to be something else.
One way to check for either is get your compiler to generate the post-processed file, i.e. the source file after it has been run through the C pre-processor but before it has been compiled. You should then be able to find your offending line and see if the map type has been replaced with something else. You should also be able to search back up the file and see what header the #include opulled in.
How you generate the post-processed file is compiler dependent - check the cmd-line flags in the docs for your compiler.