What is the difference between using and include in c++? - c++

I know that include is for classes and using is for some built-in stuff, like namespace std... When you include something, you can create objects and play around with them, but when you are "using" something, then you can use some sort of built-in functions. But then how am I supposed to create my own "library" which I could "use"?

Simply put #include tells the pre-compiler to simply copy and paste contents of the header file being included to the current translation unit. It is evaluated by the pre-compiler.
While using directive directs the compiler to bring the symbol names from another scope in to current scope. This is essentially put in effect by the compiler.
But then how am I supposed to create my own "library" which I could "use"?
Namespaces are something which are used for preventing symbol name clashes. And usually every library implementer will have their functionality wrapped up in one or many namespaces.

'include' basically does a copy-paste the value of a file to the location of the "include" line. This is used to make your source code (usually .c file) aware of a declaration of other source code (usually sits in .h file).
'using' basically tells the compiler that in the next code you are using something (usually a namespace) so you won't have to do it explicitly each time:
Instead of:
std::string a;
std::string b;
std::string c;
You could write:
using namespace std;
string a;
string b;
string c;

You can say both gives the same functionality but #include is not done by compiler where as using is done by compiler. In #include all the code is placed in file where #include is given where as namespace gives the definition of function and variables from one scope to another. If you have function with same name in two header files and both are included then there will be an error of redeclaration but you can use same name functions if they are from different namespaces.

Related

using directive in header file

I have a class that I need to convert to a template class. For this, I am moving the implementation from class.cpp to class-in.h that will then be included at the end of class.h.
The implementation has a few using ... directives as well as a gflag DEFINE_bool. I need to use these in the class-inl.h file but I am told that they shouldn't be placed in a header file.
The class-inl.h is a header file but it will never be included as a regular header file.
Is there a way I can get rid of using/ gflag in the header file? Can I put the gflag, using statements in a class.cpp?
edit: I meant using declaration example using std::cout
My recommendation is to not put usings into header files if they are only used for implementation. They unnecessarily leak symbols and implementation details. If you define using my_shortcut_for_long_type=...., someone is bound to start using it and code breaks when you decide to change it.
It won't kill you to write std::cout instead of cout. If you want to shorten a long type, place the using into e.g. impl namespace; same goes for what used to be static functions in .cpps. Do not forget to mark them inline if you decide to define them also in the header. using can also be defined inside function scope, use that too.
Definitely do not put using namespace std; or any other namespace into headers files unless that is the purpose of that header.
Refrain from using macros if possible also.
It is generally fine to place using in a header file.
Is there a way I can get rid of using ... in the header file?
Yes: Don't depend on the declaration in the header, then you don't need to declare it. But as I stated, there is generally no need to do get rid of using in a header.
Is there a way I can get rid of ... gflag in the header file?
Define it in a source file instead.

Using namespaces and includes

The question might be trivial (and possibly a duplicate).
As far as I understand, a C/C++ header file (with a using namespace in it), when used by other source files, it is copied right at the point where the #include directive was in that source file.
Also, given that a source file uses a relatively large number of include directives and that there may be a couple of "redefinitions" for the entire standard library (simply targeted at different implementations).
Here is the main question: How do I know which namespaces am I currently using at any point in the source file if the source file has no using namespace statement?
I'm reading through source files and I have no idea which namespace is being used.
One can override the namespace cleverness by using something like ::std::getline().
If there is no easy way of determining the namespace, is it fair to refactor those files, such that where say string is used to replace it with ::std::string?
If you don't have a using namespace ... directive you're not using any namespace. In general, your code should refer to things in the standard library with their full names, e.g., std::cout, std::get_line(), std::string.
Yes, you can save your self some typing at the expense of loss of clarity and sometimes mysterious compilation failures or, worse, runtime failures with using namespace std;. After that, you don't have to put std:: in front of the names of things in the standard library: cout, get_line(), string. The using directive puts those names into the global namespace, along with a bunch of sludge that you probably aren't interested in.
If you use something like using namespace std; it should appear only in a source file, never in a header. That way you can tell which namespaces have been "used" by looking at the top of the file. You shouldn't have to track through all your headers for stray using directives.
using namespace does not mean that you currently use this specific namespace. It means, that all types, variables and functions from this namespace are now in your global namespace, for this translation unit. So, you might have multiple of these statements.
This is why header files should never use using namespace. There is no easier way than using std::string within a header file, you should always be very explicit about the namespace without using namespaces.
Having used using namespace xxx, there is no way of finding out that xxx is now in global namespace, I am afraid.
using namespace does not do what you expect...
If you want to place functions, classes or variables in a namespace, you do it this way:
namespace foo
{
void f();
}
namespace bar
{
void f();
}
This declares two functions f in namespaces foo and bar respectively. The same you will find in header files; if there is no namespace specified as above, then the function/class/variable is in global namespace. Nothing more.
using namespace now allows you to use functions from a namespace without having to specify it explicitly:
// without:
foo::f();
bar::f();
f(); // unknown!
using namespace foo;
foo::f(); // still fine...
bar::f();
f(); // now you call foo::f
Be aware that this is bad practice, though (the link refers to namespace std, but same applies for all namespaces).
This is even worse in header files: there is no way to undo the effect of a declared using namespace <whatever> again – so you impose it on all users of your header, possibly causing great trouble to some of them. So please don't ever use it in header files.
There are three approaches I can think of right now:
Use the IDE: A modern development environment should be able (possibly with the help of plug-ins) to analyze your code while you edit, and tell you the authoritative qualified name of any identifier you hover the mouse cursor over.
Of course this is not an option if you are not using an IDE, and sometimes even IDEs may get confused and give you wrong information.
Use the compiler and guesswork: If you already have a hunch which namespace you might be in, you can define some object, reference it via qualified name, and see if the code compiles, like so:
const int Fnord = 1;
const int* Probe = &::solid::guess::Fnord;
One caveat is that it may give misleading results if using namespace or anonymous namespaces are involved.
Use the preprocessor: Most compilers define a preprocessor macro that tells you the name of the function it is used in, which may include the namespace; for example, on MSVC, __FUNCTION__ will do just this. If the file contains a function that you know will be executed, you can have that function tell you its authoritative qualified name at run-time, like so:
int SomeFunction(void)
{
printf("%s\n", __FUNCTION__);
}
If you can't use standard output, you might store the value in a variable and use a debugger to inspect it.
If you can find no such function, try defining a class with a static instance of itself, and placing the code in the constructor.
(Unfortunately I can't think of a way to inspect the macro's value at compile-time; static_assert came to my mind, but it can't be used inside functions, and __FUNCTION__ can't be used outside.)
The macro is not standardized though, and may not include the namespace (or it may not exist at all). On GCC for instance, __FUNCTION__ will only give you the unqualified name, and you will have to use __PRETTY_FUNCTION__ instead.
(As of C99 and C++11 there does exist a standardized alternative, __func__, but the format of the function name is unspecified, and may or may not include the namespace. On GCC it does not.)

GCC Defect with anonymous namespaces?

I have two header files that I'm including from my main.cpp that have the following definition in an anonymous namespace: const string strToken = ("%");
Compiling using g++ version 4.9 results in this:
In file included from main.cpp:25:0:
libraries/trace.h:31:14: error: redefinition of ‘const string {anonymous}::strToken’
const string strToken = ("%");
^
In file included from libraries/debuglogger.h:12:0,
from libraries/packet.h:10,
from main.cpp:20:
libraries/strformat.h:23:14: note: ‘const string {anonymous}::strToken’ previously declared here
const string strToken = ("%");
^
I had thought that putting something in an anonymous namespace limited it to file scope, making this a non-issue. Am I missing something, or is this some sort of defect in GCC? If anyone wants the full code I would be willing to include it, but I'm hoping I've included enough information in my question to not need it.
I had thought that putting something in an anonymous namespace limited it to file scope
You were just a bit off. Putting things in an anonymous namespace limits their visibility to the translation unit they appear in. A translation unit is everything that turns into a single object file, which is typically one source file (.cpp file) along with all the code from the header files that are included from that source file. So, when you have main.cpp which includes two headers that have the same declarations (in an anonymous namespace or not), you get an error.
Always think about the #include statements as being essentially just a copy-paste of the content of the header in place of the include statement. These kinds of issues become a lot easier to deal with once you understand that. For example, your particular case basically boils down to having this code after the include-statement have been resolved (copy-pasted into the source file):
// from first header:
namespace {
const string strToken = ("%");
};
// from second header:
namespace {
const string strToken = ("%");
};
int main() { ... };
where the error is pretty obvious, and anonymous namespace really won't change anything to the basic problem that you have multiple definitions of the same thing.
Anonymous namespaces are mainly there so that you can create things inside a translation unit (usually in the .cpp file itself) without having any traces of them appearing after compilation of the translation unit into an object file. You might find this tutorial helpful in understanding the whole compilation and linking process.
I've discovered after doing some research that anonymous namespaces in headers are a bad idea. See here for possible solutions: Hiding a C++ class in a header without using the unnamed namespace

"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.

visibility problems with namespaces

I have two source files, one named main.cpp (where the namespace M is defined) and the file engines.h (where several names are defined).
main.cpp includes engines.h.
engines.h need to use the stuff inside M, and M needs to use the stuff inside engines.h.
I get an error doing using namespace M; in engines.h.
Don't use using namespace inside header files. This will get all the symbols from the namespace inside each translation unit that includes that header file, so you'll have a symbol mess (name conflict, which is probably what you're facing in your situation). Use full qualification inside the header files, or at least use the using namespace statement locally (inside a function or method where you what to improve readability).
For your situation, what is the error you get? What is the content of the headers?
You cannot do using namespace M before the namespace was defined. If there is a cyclic dependency, you need to solve it by using one or more techniques
Forward declare if your uses don't need to know the members or size of classes, but just handle with pointers or references to them:
namespace M { class MyCow; }
Define stuff in engines.cc
// engines.h
void f();
// engines.cpp
#include "main.h"
void f() { MyCow muuh; }
Use of the pimpl idiom reduces dependencies even more, as it keeps headers free of headers that are only used by implementations..
Split the part in .h files for the interface and .cpp files for the implementation to handle such dependencies. That way, headers are less dependent on other headers, and implementation files can include the headers.