C++ include header problem - c++

I am new to c/c++, I am confused about followings:
Whether I should put class declarations in its own header file, and actual implementation in another file?
Whether I should put headers like <iostream> in the example.h file or in example.cpp file?
If all the classes need to use <iostream>, and I include a class's header file into another class's header, does it mean I included <iostream> twice?
If I use a lot STL classes, what is a good practice to use std::?

1.Whether I should put class declarations in its own header file,
and actual implementation in another
file?
You can write the definition of a class, and the definition of the members of the class separately in the same header file if you are manipulating templates. Also, if you want to make your members function inline, you can define them inside the class definition itself. In any other case, it is better to separate the definition of the class (.hpp file) and the definition of the members of the class (.cpp).
2.Whether I should put headers like in the example.h file or in example.cpp
file?
It Depends on if you need those headers in the example.h file or in your .cpp file only.
3.If all the classes need to use , and I include a class's header file into
another class's header, does it mean I
included twice?
It happens if you don't wrap your class definitions by the following macros:
#ifndef FOO_HPP
#define FOO_HPP
class {
...
};
#endif
5.If I use a lot STL classes, what is a good practice to use std::?
I think it is better whenever you can to use std:: each time instead of using namespace std. This way you will use only the namespaces that you need and your code will be more readable because you will avoid namespace conflicts (imagine two methods that have the same name and belong to two different namespaces).
But most importantly where is question number 4 anyway?

Generally, yes. It helps with organization. However, on small projects it may not be that big of a deal.
I'm having trouble understanding the question here. If you're asking where to put the #include directive, the implementation file should include the header file.
Yes, but the use of include guards prevents multiple inclusions.

You normally should, but for relatively small projects you may avoid having an implementation file as much as possible;
If your header is using only incomplete types from the <iostream>, you can avoid including it, but you'll need forward declarations for these types (see When to use forward declaration?). Yet, for simplicity, if the type uses template, I normally include the respective header;
No. The include guards guarantee that a header is included only once in the same translation unit;
A common good practice is to not put using namespace std in a header file. Be aware of namespace conflicts too;

Typically, you do put class declarations (including declarations of members) into header files and definitions of member functions (methods) in source files. Headers usually have names like *.h or *.hpp. As to point 3, you should put include guards into your headers so they can be safely included multiple times in the same source file; then you can include them everywhere you need them. I don't understand point #5: are you asking about when to use std:: namespace qualification?

For the "included twice" problem, here is a common pattern for your header files:
// _BLAHCLASS_H_ should be different for each header, otherwise things will Go Bad.
#ifndef _BLAHCLASS_H_
#define _BLAHCLASS_H_
... rest of header ...
#endif

As long as they're not templates, generally yes. Templates (for better or worse) have to be put in headers.
I prefer to make each of my headers "standalone", so if any other header is needed for it to function, it includes that header itself (e.g., if I have a class that uses std::string, the header for that class will #include <string>.
No. With a few special exceptions, the standard headers are required to be written so you can include them more than once without it changing anything (the primary exception is assert.h/cassert, which it can make sense to include more than once).
I'm not sure exactly what you're asking. If you're asking about a using directive like using namespace std;, then it's generally (though certainly not universally) disliked. A using declaration like using std::vector; is generally considered less problematic.

Related

Is splitting template code with inheritance the right way to go?

Currently, I am writing a few classes, all of which inherit from a base class and somehow enrich it. All of these classes use templates in order to take different elements as parameters (the classes are all variations of an abstract vector class). So I wrote all of the code in one big .hpp file because I read that splitting the code in .hpp and .cpp would cause linker problems (Splitting templated C++ classes into .hpp/.cpp files--is it possible?) and it wouldn't work.
So I was wondering, since it's not really clean and clear to have everything in a big .hpp file, should I split it and how would I do the splitting the right way in order to keep the code as intact as possible? Should I import the child classes into the base class? Do I have to forward declare all my classes in every .hpp file or not? How would the splitting interact with the templates.
If the code is necessary, I can add it. Just trying to keep it short if it isn't.
As far as splitting the code up, there is a technique for templated code where you can split up the declarations and definitions, at least visually (you'll see why I make that distinction in a moment). So you first start with the header, that will contain just your class and function declarations
Foo.h
template <typename T>
T some_foo(T x); // declaration
#include "Foo.inl"
Then you make a separate file for the implementation. Note that we #include this .inl file in our header, so as far as the compiler is concerned all of the code still exists in the header. Doing it this way is just for human readers, but this way you can split up the actual implementation code into separate files and just include them at the end of the header.
Foo.inl
<template <typename T>
T some_foo(T x) // definition
{
return x + 5;
}
Files:
header.hpp
something1.ipp
something2.ipp
something3.ipp
Content of header.hpp:
#ifndef COMPANY_PROJECT_HEADER_HPP
#define COMPANY_PROJECT_HEADER_HPP 1
#include "something1.ipp"
#include "something2.ipp"
#include "something3.ipp"
#endif
Easy peasy. #include is just a "copy-and-paste" operation so you can do what you like to arrange your files in a pleasing, and easy-to-maintain organisational structure.
All the files are headers, but I've given the "sub-headers" the extension .ipp to distinguish them.
So I wrote all of the code in one big .hpp file because I read that splitting the code in .hpp and .cpp would cause linker problems ... and it wouldn't work.
That only implies that you must not split the definition of the function templates from their declaration (or the definition of member function of a class template from the definition of the template). There is no reason to put the definition of all templates into a single header - which your post seems to imply that you did.
So I was wondering, since it's not really clean and clear to have everything in a big .hpp file, should I split it
Sure.
and how would I do the splitting the right way
Just be sure to keep the definitions of the templates in the same file that declared them - as described in the answers to the linked question. If you think that's messy, then you can put the definitions into another header and include that in the declaring header.
Do I have to forward declare all my classes in every .hpp file or not?
Only in headers that refer to the declarations, but don't need the complete definition.

How can I include only few lines of header file(read-only file) in my .c file

I need to use some part(like from line 10 to line 15) of read only .h file into .C file.
Note: I can't edit .h file, because that is not from my module. Also I can't use all the .h file variables.
Is there any way to use like this ?
As the including client code, you don't have arbitrary control over which lines in the included header are used.
Some few headers explicitly grant control by using #if #ifdef or #ifndef such that you can set some preprocessor define before including that header and affect which lines are used.
Otherwise, you can sometimes declare the variables you need to access yourself, but that's something I'd strongly discourage: as the header evolves, it's easy to end up with your declarations being different from the headers. It's especially bad in C++, where authors of header files might reasonably expect to say change class X into template <...> class XT ...; typedef XT<...> X; without breaking client's ability to recompile cleanly, but if you've declared "class X;" in your own code this will conflict with it being a template.
You've explained more concrete details of your need in a comment:
I have to use only few variables from different modules( .h files). If i use #include for all .h files, then "redundant redeclaration of 'Tabc_st', previous declaration of 'Ta[b]c_st' was here" warning will come..... – laki
I would guess some kind of "Hungarian" notation's being used, and - after recovering from nausea - assume T was for type and _st for struct. If so, you've either got multiple struct Tabc_st declarations or typedef ... Tabc_st;s. To comment on the options listed in other answers:
#include the conflicting headers in separate namespaces: this is a moderately clean, structured approach to the problem but can backfire: for example - if the header is exposing functionality that you plan to link a library for, then the mangled names won't match and linking will fail.
#define Tabc_st WhateverElse around all-but-one of the problematic headers: this works great for typedefs, but for struct Tabc_st it does mean that any uses of the type later in the header will instead see "WhateverElse" - if you're meant to be able to take a Tabc_st and use it with any of the code from any of the headers, you'll find this doesn't pan out as they're all now expecting different types.
Another approach is to provide a .h/.cpp pair that wrap each problematic .h and expose it's functionality using new non-conflicting names. That's quite a lot of work to maintain.
A workable hack may be to script up a pre-compilation step such as:
TABC_ST=`fgrep 'struct Tabc_st;' header1.h`
fgrep -v --line-regexp $TABC_ST header2.h > header2_sans_tabc.h
fgrep -v --line-regexp $TABC_ST header3.h > header3_sans_tabc.h
Then use the ..._sans_tabc.h headers....
You can do
#define Tabc_st bogus_thing_I_can_ignore
#include <readonlyheaderfile.h>
#undef Tabc_st
and the header file will declare bogus_thing_I_can_ignore instead of redeclaring Tabc_st. if Tabc_st is a typedef name and the header uses that type, this will still work because typedefs are just aliases, not new types.
If you can't edit header file, there is no way to use only part of codes. I would strongly suggest that you use different namespace to solve variable name conflicts.
And if you are trying to include only some part of codes to save memory....don't do that. Having few useless variable is not big deal.

"using namespace" in c++ headers [duplicate]

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 1 year ago.
In all our c++ courses, all the teachers always put using namespace std; right after the #includes in their .h files. This seems to me to be dangerous since then by including that header in another program I will get the namespace imported into my program, maybe without realizing, intending or wanting it (header inclusion can be very deeply nested).
So my question is double: Am I right that using namespace should not be used in header files, and/or is there some way to undo it, something like:
//header.h
using namespace std {
.
.
.
}
One more question along the same lines: Should a header file #include all the headers that it's corresponding .cpp file needs, only those that are needed for the header definitions and let the .cpp file #include the rest, or none and declare everything it needs as extern?
The reasoning behind the question is the same as above: I don't want surprises when including .h files.
Also, if I am right, is this a common mistake? I mean in real-world programming and in "real" projects out there.
Thank you.
You should definitely NOT use using namespace in headers for precisely the reason you say, that it can unexpectedly change the meaning of code in any other files that include that header. There's no way to undo a using namespace which is another reason it's so dangerous. I typically just use grep or the like to make sure that using namespace isn't being called out in headers rather than trying anything more complicated. Probably static code checkers flag this too.
The header should include just the headers that it needs to compile. An easy way to enforce this is to always include each source file's own header as the first thing, before any other headers. Then the source file will fail to compile if the header isn't self-contained. In some cases, for example referring to implementation-detail classes within a library, you can use forward declarations instead of #include because you have full control over the definition of such forward declared class.
I'm not sure I would call it common, but it definitely shows up once in a while, usually written by new programmers that aren't aware of the negative consequences. Typically just a little education about the risks takes care of any issues since it's relatively simple to fix.
Item 59 in Sutter and Alexandrescu's "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices":
59. Don’t write namespace usings in a header file or before an #include.
Namespace usings are for your convenience, not for you to inflict on others: Never write a using declaration or a using directive before an #include directive.
Corollary: In header files, don't write namespace-level using directives or using declarations; instead, explicitly namespace-qualify all names.
A header file is a guest in one or more source files. A header file that includes using directives and declarations brings its rowdy buddies over too.
A using declaration brings in one buddy. A using directive brings in all the buddies in the namespace. Your teachers' use of using namespace std; is a using directive.
More seriously, we have namespaces to avoid name clash. A header file is intended to provide an interface. Most headers are agnostic of what code may include them, now or in the future. Adding using statements for internal convenience within the header foists those convenient names on all the potential clients of that header. That can lead to name clash. And it's just plain rude.
You need to be careful when including headers inside of headers. In large projects, it can create a very tangled dependency chain that triggers larger/longer rebuilds than were actually necessary. Check out this article and its follow-up to learn more about the importance of good physical structure in C++ projects.
You should only include headers inside a header when absolutely needed (whenever the full definition of a class is needed), and use forward declaration wherever you can (when the class is required is a pointer or a reference).
As for namespaces, I tend to use the explicit namespace scoping in my header files, and only put a using namespace in my cpp files.
With regards to "Is there some way to undo [a using declaration]?"
I think it is useful to point out that using declarations are affected by scope.
#include <vector>
{ // begin a new scope with {
using namespace std;
vector myVector; // std::vector is used
} // end the scope with }
vector myOtherVector; // error vector undefined
std::vector mySTDVector // no error std::vector is fully qualified
So effectively yes. By limiting the scope of the using declaration its effect only lasts within that scope; it is 'undone' when that scope ends.
When the using declaration is declared in a file outside of any other scope it has file-scope and affects everything in that file.
In the case of a header file, if the using declaration is at file-scope this will extend to the scope of any file the header is included in.
Check out the Goddard Space Flight Center coding standards (for C and C++). That turns out to be a bit harder than it used to be - see the updated answers to the SO questions:
Should I use #include in headers
Self-sufficient headers in C and C++
The GSFC C++ coding standard says:
§3.3.7 Each header file shall #include the files it needs to compile, rather than forcing users to #include the needed files. #includes shall be limited to what the header needs; other #includes should be placed in the source file.
The first of the cross-referenced questions now includes a quote from the GSFC C coding standard, and the rationale, but the substance ends up being the same.
You are right that using namespace in header is dangerous.
I do not know a way how to undo it.
It is easy to detect it however just search for using namespace in header files.
For that last reason it is uncommon in real projects. More experienced coworkers will soon complain if someone does something like it.
In real projects people try to minimize the amount of included files, because the less you include the quicker it compiles. That saves time of everybody. However if the header file assumes that something should be included before it then it should include it itself. Otherwise it makes headers not self-contained.
You are right. And any file should only include the headers needed by that file. As for "is doing things wrong common in real world projects?" - oh, yes!
Like all things in programming, pragmatism should win over dogmatism, IMO.
So long as you make the decision project-wide ("Our project uses STL extensively, and we don't want to have to prepend everything with std::."), I don't see the problem with it. The only thing you're risking is name collisions, after all, and with the ubiquity of STL it's unlikely to be a problem.
On the other hand, if it was a decision by one developer in a single (non-private) header-file, I can see how it would generate confusion among the team and should be avoided.
I believe you can use 'using' in C++ headers safely if you write your declarations in a nested namespace like this:
namespace DECLARATIONS_WITH_NAMESPACES_USED_INCLUDED
{
/*using statements*/
namespace DECLARATIONS_WITH_NO_NAMESPACES_USED_INCLUDED
{
/*declarations*/
}
}
using namespace DECLARATIONS_WITH_NAMESPACES_USED_INCLUDED::DECLARATIONS_WITH_NO_NAMESPACES_USED_INCLUDED;
This should include only the things declared in 'DECLARATIONS_WITH_NO_NAMESPACES_USED_INCLUDED' without the namespaces used. I have tested it on mingw64 compiler.

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

#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;