Avoid recursive(?) #include declarations - c++

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.

Related

Recursion in includes (file 1 includes file 2 that includes file1)

I have been looking around but I have not found any question that really helps me to solve this issue. I am not very experienced, so maybe this problem is trivial and it is a question of my lack of knowledge.
I am trying to solve an issue. Our system has a Logger that takes different logs and puts them into a SharedMemory.
However, from one of our classes (a StateMachine) I can not use the Loogger because of recursion:
Logger.h includes SharedMemory.h
SharedMemory.h includes StateMachine.h
If I include Logger.h in StateMachine.h, compile errors appear everywhere. First i was trying to fix this problem by creating a second SharedMemory that is dedicated exclusively to the Logger and don't include StateMachine.h.
With this approach, the compilation errors were solved, but my manager does not like this design solution.
I have also tried to change include order, and to declare class before the include but it is not working (e.g. declare class SharedMachine; before #include SharedMachine.h)
The includes are like this:
In the StateMachine.h
#ifndef SM_H
#define SM_H
#include <map>
/* (different includes) */
#include Logger.h
In the Logger.h
#include SharedMemory.h
In the SharedMemory.h
#include StateMachine.h
I would like to know if there is any trick that I can use to make the includes work in this way, without architectural changes (that my manager seems not to like).
Try to move includes from header files to source (*.cpp) files
Use forward declarations: What are forward declarations in C++?
Change interfaces to work with pointers or references to needed types instead of using actual types, to make possible using forward declaration (if needed)

Where should I put C++ #include's? In the header or in the implementation?

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.

local #includes

Is there some way to #include standard things locally (for one function, one class, etc... at a time) instead of globally. Taking a very simple example one might want to use std::string but it is only needed in one class and you don't want the overhead of it existing everywhere.
Instead of making #include local, you should probably just move the class that requires it into a separate file.
Since #include is simply just a kind of text replacement before compilation (by the preprocessor), it is just a matter of where you put the include statement.
Likely, you are refering to "locally" as "in just one .cpp file" and to "globally" as "in all .cpp files".
If this is true, you can make an #include as "locally" by only including in that .cpp files where you want it. If you want to include a file with one #include statement in several files, place the include statement into a .h file and include that .h file inside all required files.
A good place to make a "global" #include is the .h header file that serves as the precompiled header.
One way to do the thing you want is use a nested class like class IMPL and use a pointer to that as a member in your class. you define and implement that your_class::IMPL in separate files. That way you achief total data hiding.
You could put the definition of std::string in a local header (that's it, located in your project directory).
This is not an easy job, anyway, especially for a template class like std::string: since it's a template it'll need the whole declaration, and your program, at runtime, will use the std::string as declared in your header.
Besides different STL implementations could implement std::string in different ways, although the interface should be the same.
So the short answer is: no, use the system headers.
Well, if you will #include something in a .cpp file , you will not get access to this header in other files. But if you #include a.h in a b.h file and then #include b.h in c.cpp i think you will have access to a.h in c.cpp

C++ STL map typedef errors

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.

#include header style

I have a question regarding "best-practice" when including headers.
Obviously include guards protect us from having multiple includes in a header or source file, so my question is whether you find it beneficial to #include all of the needed headers in a header or source file, even if one of the headers included already contains one of the other includes. The reasoning for this would be so that the reader could see everything needed for the file, rather than hunting through other headers.
Ex: Assume include guards are used:
// Header titled foo.h
#include "blah.h"
//....
.
// Header titled bar.h that needs blah.h and foo.h
#include "foo.h"
#include "blah.h" // Unnecessary, but tells reader that bar needs blah
Also, if a header is not needed in the header file, but is needed in it's related source file, do you put it in the header or the source?
In your example, yes, bar.h should #include blah.h. That way if someone modifies foo so that it doesn't need blah, the change won't break bar.
If blah.h is needed in foo.c but not in foo.h, then it should not be #included in foo.h. Many other files may #include foo.h, and more files may #include them. If you #include blah.h in foo.h, then you make all those files needlessly dependent on blah.h. Needless dependencies cause lots of headaches:
If you modify blah.h, all those files must be recompiled.
If you want to isolate one of them (say, to carry it over to another project or build a unit test around it) you have to take blah.h along.
If there's a bug in one of them, you can't rule out blah.h as the cause until you check.
If you are foolish enough to have something like a macro in blah.h... well, never mind, in that case there's no hope for you.
The basic rule is, #include any headers that you actually use in your code. So, if we're talking:
// foo.h
#include "utilities.h"
using util::foobar;
void func() {
foobar();
}
// bar.h
#include "foo.h"
#include "utilities.h"
using util::florg;
int main() {
florg();
func();
}
Where bar.h uses tools from the header included twice, then you should #include it, even if you don't necessarily have to. On the other hand, if bar.h doesn't need any functions from utilities.h, then even though foo.h includes it, don't #include it.
The header for a source file should define the interface that the users of the code need to use it accurately. It should contain all that they need to use the interface, but nothing extra. If they need the facility provided by xyz.cpp, then all that is required by the user is #include "xyz.h".
How 'xyz.h' provides that functionality is largely up to the implementer of 'xyz.h'. If it requires facilities that can only be specified by including a specific header, then 'xyz.h' should include that other header. If it can avoid including a specific header (by forward definition or any other clean means), it should do so.
In the example, my coding would probably depend on whether the 'foo.h' header was under the control of the same project as the 'blah.h' header. If so, then I probably would not make the explicit second include; if not, I might include it. However, the statements above should be forcing me to say "yes, include 'foo.h' just in case".
In my defense, I believe the C++ standard allows the inclusion of any one of the C++ headers to include others - as required by the implementation; this could be regarded as similar. The problem is that if you include just 'bar.h' and yet use features from 'blah.h', then when 'bar.h' is modified because its code no longer needs 'blah.h', then the user's code that used to compile (by accident) now fails.
However, if the user was accessing 'blah.h' facilities directly, then the user should have included 'blah.h' directly. The revised interface to the code in 'bar.h' does not need 'blah.h' any more, so any code that was using just the interface to 'bar.h' should be fine still. But if the code was using 'blah.h' too, then it should have been including it directly.
I suspect the Law of Demeter also should be considered - or could be viewed as influencing this. Basically, 'bar.h' should include the headers that are needed to make it work, whether directly or indirectly - and the consumers of 'bar.h' should not need to worry much about it.
To answer the last question: clearly, headers needed by the implementation but not needed by the interface should only be included in the implementation source code and absolutely not in the header. What the implementation uses is irrelevant to the user and compilation efficiency and information hiding both demand that the header only expose the minimum necessary information to the users of the header.
Including everything upfront in headers in C++ can cause compile times to explode
Better to encapsulate and forward declare as much as possible. The forward declarations provide enough hints to what is required to use the class. Its quite acceptable to have standard includes in there though (especially templates as they cannot be forward declared).
My comments might not be a direct answer to your question but useful.
IOD/IOP encourages that put less headers in INTERFACE headers as possible, the main benefits to do so:
less dependencies;
smaller link-time symbols scope;
faster compiling;
smaller size of final executables if header contains static C-style function definitions etc.
per IOD/IOP, should interfaces only be put in .h/.hxx headers. include headers in your .c/.cpp instead.
My Rules for header files are:
Rule #1
In the header file only #include class's that are members or base classes of your class.
If your class has pointers or references used forward declarations.
--Plop.h
#include "Base.h"
#include "Stop.h"
#include <string>
class Plat;
class Clone;
class Plop: public Base
{
int x;
Stop stop;
Plat& plat;
Clone* clone;
std::string name;
};
Caviat: If your define members in the header file (example template) then you may need to include Plat and Clone (but only do so if absolutely required).
Rule #2
In the source put header files from most specific to least specific order.
But don't include anything you do not explicitly need too.
So in this case you will inlcude:
Plop.h (The most specific).
Clone.h/Plat.h (Used directly in the class)
C++ header files (Clone and Plat may depend on these)
C header files
The argument here is that if Clone.h needs map (and Plop needs map) and you put the C++ header files closer to the top of the list then you hide the fact that Clone.h needs map thus you may not add it inside Clone.h.
Rule #3
Always use header guards
#ifndef <NAMESPACE1>_<NAMESPACE2>_<CLASSNAME>_H
#define <NAMESPACE1>_<NAMESPACE2>_<CLASSNAME>_H
// Stuff
#endif
PS: I am not suggesting using multiple nested namespaces. I am just demonstrating how I do if I do it. I normal put everything (apart from main) in a namespace. Nesting would depend on situation.
Rule #4
Avoid the using declaration.
Except for the current scope of the class I am working on:
-- Stop.h
#ifndef THORSANVIL_XXXXX_STOP_H
#define THORSANVIL_XXXXX_STOP_H
namespace ThorsAnvil
{
namespace XXXXX
{
class Stop
{
};
} // end namespace XXXX
} // end namespace ThorsAnvil
#endif
-- Stop.cpp
#include "Stop.h"
using namespace ThorsAnvil:XXXXX;