Where is namespace std defined? - c++

I want to take a peek inside of namespace std but, i'm not able to actually find the file on my computer where it is defined. I tried googling this but, i haven't had much luck.

On most Unix systems, the C++ headers are usually stored in /usr/include/c++/<version>/, where <version> is the GCC/libstdc++ version (i.e. 4.9 or 4.9.2), or else the libc++ version i.e. v1.
Within that directory are all (or just most?) of the standard-mandated headers, which are mostly just ordinary C++ code. For libstdc++, note in particular that most of the older headers just include something in bits/; few of the C++11-specific headers do this.

A list of every thing included in namespace std can be found here.
If you are using Visual Studio you can find it locally here :
~\Microsoft Visual Studio\VC\crt\src
There is also an online representation here.
NOTE : Edit the src files at your own risk, I'd recommend not editing them at all.

Many of the things implemented in the std namespace are templated, which means their entire implementation will be in the header files. For example, std::vector should be in the vector header file. Simply look at the options for your compiler to find out where those header files are located.
There may be some non-templated parent classes and free standing functions, which will not be in the headers. Again, look at the compiler documentation to see if the source files are included somewhere and where they would be.

Related

what are the paths that resolve the scope of the std library

So, I believe I understand the concept of the header method C++. But I read a post which become confusing. If I decide to avoid using directive in my programming I.E (using namespace std), how can I supplement other libraries that I may not be familiar with or where can I find a digital resource to help me resolve scope problems. I know that the "std" part in a std::cout statement resolves the the function from the iostream when I choice to include it. However, I am not getting the convention here. What would the scope parameter for be in a situation where I wanted to use the it but did not want to use the std namespace and how would this affect un-conventional classes?
Files which contain standart functions declarations - like iostream for example, are kept in directories depending on what ide you are using. For example, for Visual c++ studio 2008 these files are in [visual studio folder]/VC/include.
To find all files containing std namespace functions declarations you probably will need to search for all files containing _STD_BEGIN macro.

Can C++ Headers be called vector.h or matrix.h?

I have including problems in a C++ Project. I included math.h, but there are strange problems with my vector.h and my matrix.h header files. Am I allowed to call these files vector.h and matrix.h?
Two headers cannot have the same name.
By same name, the full path name is implied, so
#inlcude "testClass.h"
#include "heders/testClass.h" // OK, distinguishable
Visual studio prevents you from adding a header having a name that already exists in the project.
You should also check that your header is actually included in your project (or through your Makefile, build system etc). A quick check would be to cause a syntactic error in that header and see if it breaks the build
So to get back to your question, do you already have headers called vector.h and matrix.h? Cause that would be the only thing preventing you from naming new headers like that.
Keep in mind that headers accessed with #include <...> require their folder to be set as an include (external) directory so qualifying up to that path won't work
In theory I don't know of anything to prohibit doing so.
I'd consider vector.h close enough to <vector> that using it would be a poor idea.
I'm not exactly excited about matrix.h either, but at least it's not nearly so obviously a poor choice.
Of course, for any header you wrote yourself (rather than one provided by the tools you're using) you want to enclose the name in quotes, not angle brackets.
The rationale why C++ chose the unusual <vector> format without suffix is because the intent was to remain compatbile with existing C code which might very well have "vector.h". So the answer is yes, by design.

Show an error (in Visual studio), when someone tries to use STL in a current .cpp or .h file

In our company sometimes we write .cpp and .h files, which are used in projects for old WM (we use Embedded Visual C++ 3.0 or something for this) and in more modern code (VS 2010).
This Embedded Visual C++ does not support STL.
So if one of developers, who works in VS2010, changes a file, which is shared, and adds some function, which uses std::vector, for instance, on his side everything will be OK, but the build (which is quite long) will fail.
So to see this mistake sooner, I would like to add something like
#if defined(%%STL%%)
#error("!!!!")
#endif
in all files, which are compiled with old toolset. In this case the developer could see compile time error even in VS2010.
But I could not find what I can put instead %%STL%% there.
Any ideas? Or maybe someone knows a better way how I can do this?
Based on a comment to the question, you could go through each of the header files that aren't supported and see what symbols they define for their include guard. Then check for those symbols being defined.
E.G. The Microsoft C++ header <algorithm> defines _ALGORITHM_ so you can check for that:
#ifdef _ALGORITHM_
#error("<algorithm> included")
#endif
A bunch of these could be collected up and put into a single header file that you could include in each shared source file, at the end.
There is quite a nice solution (at least I do not see pitfalls)
%%STL%% should be _STD_BEGIN
this macro is used for "namespace std {" in VS stl implementation

<iostream> vs. <iostream.h> vs. "iostream.h"

When including a header file in C++, what's the difference between...
including the .h part versus not including .h part when wrapping it in <> signs?
#include <iostream> vs. #include <iostream.h>
wrapping the header name in double quotes versus wrapping it in < > signs?
#include <iostream.h> vs. #include "iostream.h"
In short:
iostream.h is deprecated—it is the original Stroustrup version. iostream is the version from the standards committee. Generally, compilers point them both to the same thing, but some older compilers won't have the older one. In some odd cases, they will both exist and be different (to support legacy code) and you then must be specific.
"" versus <> simply means check the local directories for the header before going to the library (in most compilers).
Here is a decent link article.
To summarize, the reason given:
The version of the iostream library that the Standards Committee
produced was quite a bit different from the CFront implementation.
{snip}
To ease transition, the C++ Standards Committee declared that code
including the standard C++ headers would use include directives that
lack an extension. This allowed compiler vendors to ship the old style
C++ library headers with the .h extension and the new style headers
without.
An advantage of not using the .h version:
There are several reasons why new code should be written using the
extensionless version of the header files instead of the .h forms. The
first is the unpredictability of such code when compiled on modern
compilers. As previously mentioned, the result of using the .h headers
is implementation specific. And as time goes by, the chance that a
given compiler will have the old style library available decreases.
As the person on the standards committee (X3J16) who proposed leaving off the .h, my original intent was to settle the debate over .h, .H, .hpp, .hxx, or .h++ file extensions; or a desire by some that there be no implication in the standard that this was the name of a file on disk in order to allow an IDE to pull pre-compiled header information out of somewhere internal, like a resource file or even the guts of the compiler.
While Unix considered the filename to be a single string and did not actually recognize the concept of an extension, DEC operating systems had a tradition of separating the name from the extension, and supplying the "default extension" if it was omitted in particular contexts. That's where I got the idea from of leaving it up to the implementation to use whatever extension the implementation wanted to use, and it allowed the implementation to not even have this a file on disk. (I was DEC's representative on the committee at the time.)
Differentiating between the standard and the pre-standard headers was an added benefit.
The standard way (and the only one guaranteed to work) is <iostream>. On gcc, <iostream.h> (which might need to be included as <backward/iostream.h>) pulls the relevant declarations to the global namespace (so you do not need the std:: namespace prefix).
"iostream.h" would try first from the directory with your source code, since "" is meant for headers from your project. <> should always be used for system headers, and "" for your own headers.
Typically <> is used for system or standard library files whereas "" is used for project files. I would not be surprised if your compiler searches locally and when it cannot find it it defaults to the standard library version.
As for the .h, I don't think that it actually matters if you use C.
In C++, I remember vaguely that there was a newer version and an older version and that without the h it was supposed to be the new version, but I'm not even sure the old version still exists.
These are really two different questions.
The difference between the .h and
extensionless headers with the same
name is historical. The ones with
the .h extension are from the
original C++ standard which did not
have some modern features such as
namespaces and templates. It was
simpler for the new standard to put
that same functionality in new
header files to be able to use these
new features and keep the old (.h)
files for backward compatibility of
legacy code.
The difference between the #include
<...> and #include "..." format is
the order in which the compiler
looks for files. This is generally
implementation dependent, but the
idea is that the <> format looks in
system include directories first,
while "" looks in the same directory
as the source file that #included it
first.
The simple answer to the first answer is that iostream.h doesn't exist, at least in the GCC implementation. If you're on a Unix-like system, type
% locate iostream.h
/usr/include/c++/3.4.3/backward/iostream.h
and
% locate iostream
/usr/include/c++/3.4.3/iostream
/usr/include/c++/3.4.3/backward/iostream.h
As Zee's article says, iostream.h is for backward compatibility.
Regarding the names of the standard C++ header files, in the early days (the first two years) of X3J16, we faced an argument over what the extension should be on the standard C++ header files.
In use at the time by various vendors (and influenced by constraints that some operating systems placed on file names) I believe there were .h, .H, .h++, .hpp, .HXX, and possibly others. In a library group meeting I suggested that we leave the extension off, and leave it up to the implementation to supply a default file extension of its choosing if there was none in the include line, or use the name as a key in a database of pre-compiled header files if desired.
(While Unix-like systems treat the filename and 'extension' as a single string, I was representing DEC on the committee, and many DEC operating systems stored the extension in the directory as a separate field from the name. So DEC operating systems had a strong tradition of applying a default extension based on what program was accessing the file for what purpose. Telling an assembler 'X,Y=Z' might result in reading input file Z.MAC (macro) and writing output files X.OBJ and Y.LST.)
Anyway, it avoided a long, no-win debate, so the group went along with it, and Andy Koenig presented the group's conclusions on this (among others) to the entire committee which accepted it. I find it somewhat amusing that implementations missed the whole point that they could apply a default extension of their choice (which I would think would be useful to editors and other tools) and just left the extension off of the file name.
The compiler is free to add a missing ".h" (or whatever it wants) to a standard header name in order to determine the name of the actual disk file to read, if the compiler indeed gets standard headers from actual disk files. So the user program can say "#include <iostream>" and the compiler could be smart enough to open up a file named "iostream.h" (or whatever it wants) in some directory it knows about (or is told about via command line switches). The standard does not require the standard header to be in an actual disk file of text with any particular name.

How should I detect unnecessary #include files in a large C++ project?

I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary #include directives. Sometimes the #includes are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the .cpp file. Are there any good tools for detecting both of these cases?
While it won't reveal unneeded include files, Visual studio has a setting /showIncludes (right click on a .cpp file, Properties->C/C++->Advanced) that will output a tree of all included files at compile time. This can help in identifying files that shouldn't need to be included.
You can also take a look at the pimpl idiom to let you get away with fewer header file dependencies to make it easier to see the cruft that you can remove.
PC Lint works quite well for this, and it finds all sorts of other goofy problems for you too. It has command line options that can be used to create External Tools in Visual Studio, but I've found that the Visual Lint addin is easier to work with. Even the free version of Visual Lint helps. But give PC-Lint a shot. Configuring it so it doesn't give you too many warnings takes a bit of time, but you'll be amazed at what it turns up.
There's a new Clang-based tool, include-what-you-use, that aims to do this.
!!DISCLAIMER!! I work on a commercial static analysis tool (not PC Lint). !!DISCLAIMER!!
There are several issues with a simple non parsing approach:
1) Overload Sets:
It's possible that an overloaded function has declarations that come from different files. It might be that removing one header file results in a different overload being chosen rather than a compile error! The result will be a silent change in semantics that may be very difficult to track down afterwards.
2) Template specializations:
Similar to the overload example, if you have partial or explicit specializations for a template you want them all to be visible when the template is used. It might be that specializations for the primary template are in different header files. Removing the header with the specialization will not cause a compile error, but may result in undefined behaviour if that specialization would have been selected. (See: Visibility of template specialization of C++ function)
As pointed out by 'msalters', performing a full analysis of the code also allows for analysis of class usage. By checking how a class is used though a specific path of files, it is possible that the definition of the class (and therefore all of its dependnecies) can be removed completely or at least moved to a level closer to the main source in the include tree.
I don't know of any such tools, and I have thought about writing one in the past, but it turns out that this is a difficult problem to solve.
Say your source file includes a.h and b.h; a.h contains #define USE_FEATURE_X and b.h uses #ifdef USE_FEATURE_X. If #include "a.h" is commented out, your file may still compile, but may not do what you expect. Detecting this programatically is non-trivial.
Whatever tool does this would need to know your build environment as well. If a.h looks like:
#if defined( WINNT )
#define USE_FEATURE_X
#endif
Then USE_FEATURE_X is only defined if WINNT is defined, so the tool would need to know what directives are generated by the compiler itself as well as which ones are specified in the compile command rather than in a header file.
Like Timmermans, I'm not familiar with any tools for this. But I have known programmers who wrote a Perl (or Python) script to try commenting out each include line one at a time and then compile each file.
It appears that now Eric Raymond has a tool for this.
Google's cpplint.py has an "include what you use" rule (among many others), but as far as I can tell, no "include only what you use." Even so, it can be useful.
If you're interested in this topic in general, you might want to check out Lakos' Large Scale C++ Software Design. It's a bit dated, but goes into lots of "physical design" issues like finding the absolute minimum of headers that need to be included. I haven't really seen this sort of thing discussed anywhere else.
Give Include Manager a try. It integrates easily in Visual Studio and visualizes your include paths which helps you to find unnecessary stuff.
Internally it uses Graphviz but there are many more cool features. And although it is a commercial product it has a very low price.
You can build an include graph using C/C++ Include File Dependencies Watcher, and find unneeded includes visually.
If your header files generally start with
#ifndef __SOMEHEADER_H__
#define __SOMEHEADER_H__
// header contents
#endif
(as opposed to using #pragma once) you could change that to:
#ifndef __SOMEHEADER_H__
#define __SOMEHEADER_H__
// header contents
#else
#pragma message("Someheader.h superfluously included")
#endif
And since the compiler outputs the name of the cpp file being compiled, that would let you know at least which cpp file is causing the header to be brought in multiple times.
PC-Lint can indeed do this. One easy way to do this is to configure it to detect just unused include files and ignore all other issues. This is pretty straightforward - to enable just message 766 ("Header file not used in module"), just include the options -w0 +e766 on the command line.
The same approach can also be used with related messages such as 964 ("Header file not directly used in module") and 966 ("Indirectly included header file not used in module").
FWIW I wrote about this in more detail in a blog post last week at http://www.riverblade.co.uk/blog.php?archive=2008_09_01_archive.xml#3575027665614976318.
Adding one or both of the following #defines
will exclude often unnecessary header files and
may substantially improve
compile times especially if the code that is not using Windows API functions.
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
See http://support.microsoft.com/kb/166474
If you are looking to remove unnecessary #include files in order to decrease build times, your time and money might be better spent parallelizing your build process using cl.exe /MP, make -j, Xoreax IncrediBuild, distcc/icecream, etc.
Of course, if you already have a parallel build process and you're still trying to speed it up, then by all means clean up your #include directives and remove those unnecessary dependencies.
Start with each include file, and ensure that each include file only includes what is necessary to compile itself. Any include files that are then missing for the C++ files, can be added to the C++ files themselves.
For each include and source file, comment out each include file one at a time and see if it compiles.
It is also a good idea to sort the include files alphabetically, and where this is not possible, add a comment.
If you aren't already, using a precompiled header to include everything that you're not going to change (platform headers, external SDK headers, or static already completed pieces of your project) will make a huge difference in build times.
http://msdn.microsoft.com/en-us/library/szfdksca(VS.71).aspx
Also, although it may be too late for your project, organizing your project into sections and not lumping all local headers to one big main header is a good practice, although it takes a little extra work.
If you would work with Eclipse CDT you could try out http://includator.com to optimize your include structure. However, Includator might not know enough about VC++'s predefined includes and setting up CDT to use VC++ with correct includes is not built into CDT yet.
The latest Jetbrains IDE, CLion, automatically shows (in gray) the includes that are not used in the current file.
It is also possible to have the list of all the unused includes (and also functions, methods, etc...) from the IDE.
Some of the existing answers state that it's hard. That's indeed true, because you need a full compiler to detect the cases in which a forward declaration would be appropriate. You cant parse C++ without knowing what the symbols mean; the grammar is simply too ambiguous for that. You must know whether a certain name names a class (could be forward-declared) or a variable (can't). Also, you need to be namespace-aware.
Maybe a little late, but I once found a WebKit perl script that did just what you wanted. It'll need some adapting I believe (I'm not well versed in perl), but it should do the trick:
http://trac.webkit.org/browser/branches/old/safari-3-2-branch/WebKitTools/Scripts/find-extra-includes
(this is an old branch because trunk doesn't have the file anymore)
If there's a particular header that you think isn't needed anymore (say
string.h), you can comment out that include then put this below all the
includes:
#ifdef _STRING_H_
# error string.h is included indirectly
#endif
Of course your interface headers might use a different #define convention
to record their inclusion in CPP memory. Or no convention, in which case
this approach won't work.
Then rebuild. There are three possibilities:
It builds ok. string.h wasn't compile-critical, and the include for it
can be removed.
The #error trips. string.g was included indirectly somehow
You still don't know if string.h is required. If it is required, you
should directly #include it (see below).
You get some other compilation error. string.h was needed and isn't being
included indirectly, so the include was correct to begin with.
Note that depending on indirect inclusion when your .h or .c directly uses
another .h is almost certainly a bug: you are in effect promising that your
code will only require that header as long as some other header you're using
requires it, which probably isn't what you meant.
The caveats mentioned in other answers about headers that modify behavior
rather that declaring things which cause build failures apply here as well.