today i saw the C++ namespace,i suffer a problem.
what does the compiler does with namespace?
for example:
we write
#include<iostream>
using namespace std;
then the question coming ,what is the relationship between the iostream file and the namespace std? and where is the std defined ,in what file? when i use #include <iostream.h>, i know the compiler will bring the declare from iostream.h like "cout", "cin".etc to my cpp file.
can you give some suggestion? thank you in advance.
read this, it explains about namespaces
http://www.cplusplus.com/doc/tutorial/namespaces/
<iostream> contains items from the namespace std. You can look at a namespace as a grouping of methods, class definitions and variables. Using namespaces makes them easier to group by functionality.
The using directive just imports all contents of the namespace in the global namespace. But you don't have to use it:
You can either use:
using namespace std;
cout << "whatever";
or
std::cout << "whatever";
The reason for this is that the compiler doesn't know what cout is outside the namespace.
Think of it as declared like:
//file <iostream>
namespace std
{
//declaration of cout
}
//file <vector>
namespace std
{
//declaration of vector
}
the situation is like you searching for something in a library. iostream is the book and std is the page and cout is the line or paragraph.
NB: the same page can exist in multiple books
read about namespaces here.
Related
this is my first question here, I've searched it all over for a long time yet no solution.
I'm using QUadprog++ to solve a quadratic problem. When I use it in a test alone, it was alright. But when I implement it into my project, which contains Eigen, the Eigen operations will have errors like "Matrix A has no member named ‘lu_inverse’". If I comment the header files of Quadprog++ (Array.hh and Quadprog++.hh) out, the errors just disappear. So I assume that it was a conflict error between the header files of Eigen and Quadprog++. Does anyone have some clue? Thanks in advance!
You can also switch to one of QuadProgpp versions which can work with Eigen types directly: https://github.com/asherikov/QuadProgpp, https://www.cs.cmu.edu/~bstephe1/eiquadprog.hpp; or try an alternative implementation of the same algorithm (also Eigen based) https://github.com/asherikov/qpmad.
if your using namespace quadprogpp; then dont. your different libraries have the same typenames and thats causing the errors you have. It may be a few more characters to type quadprogpp::someFunction(); but its worth it. This is also why you shouldn't ever put a using namespace in a header ever. Its because you pollute all files that include that header with the namespace symbols and name conflicts can ensue which is the same kind of error your having right now.
the Quadprog library is in it's own namespace.
#if !defined(_ARRAY_HH)
#define _ARRAY_HH
#include <set>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
namespace quadprogpp {
enum MType { DIAG };
template <typename T>
class Vector
notice how just after the #includes there is a decleration of namespace quadprogpp{} and everything that is defined in its enclosing brackets will be defined in scope to quadprogpp, so to use any of this library you have to prefix eveything with the namespace name. this is no different than using things from the standard library. I'm quite sure you've written the standard c++ hello world
#include<iostream>
int main()
{
std::cout << "hello world!" << std::endl;
return 0;
}
cout and endl being part of namespace std have to be prefixed with std:: to access them. Many new programmers to c++ dislike this and one of the very first things they google is how to not have to type out namespaces.
#include<iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
return 0;
}
the next thing new programmers often do is learn to place their definitions in header files and their program logic in cpp files. Thats when they commit the next common mistake.
#ifndef MYHEADER
#define MYHEADER
#include<string>
#include<vector>
#include<iostream>
using namespace std; //Never do this in a header.
doing that pollutes all of your code with everything in the standard library. That may seem like a trivial thing but when you start using another library or perhaps you create your own type that has the same name as things in the standard library that causes name collisions.
That's when the compiler simply cant reason about which Vector you want. But both Quadprog.hh and Array.hh in Quadprog++ are wrapped in namespace quadprogpp to specifically prevent name collision, which is the whole purpose of namespaces. So there is somewhere in your code, likely a header file, where you've made the statement of using namespace quadprogpp;, or some other namespace that defines an Array type, and the compiler can't deduce which type your referring to in your code.
Other than removing your using namespace statements you can also prefix a typename with its namespace qualifer to disambiguate which type your talking about. In your case I'm confident your Array should be declared as quadprogpp::Array arraynamme; rather than simply Array arrayname;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have searched this question in Google. I found some related question in stackoverflow.com and quora.com but i am still not clear about this two topics. Everyone says that we use #include<iostream> for input/output operation. Now, we take input using cin and print output using cout that means this two should be defined in #include<iostream>. But without using using namespace stdwe still can't take any input nor can print something on console. So, my questions are-
Where is cin and cout actually declared and defined? Is it in #include<iostream>or in namespace std?
If in #include<iostream>why should we use using namespace std?
If in namespace std why should we use #include<iostream?
After reading some article on the web and watching some videos on YouTube, I'm assuming cout and cin is defined in namespace std and the namespace std doesn't make any sense alone because it is defined in #include<iostream>. That's why we need to use them both. (Just my thought let me know if I am right or not.)
The purpose of this question is to be clear about this two facts. If you can help it would be great.
cin and cout are defined in the header iostream and in the namespace std. These concepts are orthogonal. iostream is a file name and std is a namespace used by the source code of that file.
As a way of keeping things organized, c++ provides namespaces. All of the standard library is defined within the namespace called std. Other libraries you might write or include may use their own namespace. For example, you might include a physics library in your project which wants to define the concept of algebraic vectors. By using it's own namespace (let's called if physlib) it can differentiate between it's vector (physlib::vector) and the standard vector (std::vector). Namespaces can also be nested to help organize large projects. For example, time keeping parts of the standard library are in std::chrono and file system related components are in std::filesystem.
The preferred way of using cin and cout is as following. :
#include <iostream>
int main()
{
std::cout << "Hello, World!\n";
return 0;
}
The statement using namespace std is simply an instruction to look in the namespace std by default. It allows you to omit the std:: part of using standard library components. It's generally regarded as a bad idea to used using namespace std.
Why should we use #include <iostream>
To bring the standard library's I/O functionality into our program.
while we are using using namespace std?
This allows us to use that functionality without writing std:: each time we do.
This is unrelated to the previous step. Writing only using namespace std does not bring I/O functionality into your program, and writing only #include <iostream> does not allow us to use that functionality without writing its components' names out in full (including the std:: prefix).
The #include directive determines what we can use;
The using namespace declaration determines how we can use it.
Perfectly fine:
#include <iostream>
int main()
{
std::cout << "Hello world!\n";
}
Also valid:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!\n";
}
Not valid:
int main()
{
std::cout << "Hello world!\n";
}
And neither is this:
using namespace std;
int main()
{
std::cout << "Hello world!\n";
}
or this:
using namespace std;
int main()
{
cout << "Hello world!\n";
}
#include <iostrem> tells the compiler to pull in the contents of the header iostream. That header provides, among other things, declarations of the objects std::cin and std::cout. So the basic "Hello, world" program looks like this:
#include <iostream>
int main() {
std::cout << "Hello, world\n";
return 0;
}
Similarly, if you want to use std::vector, you tell the compiler about it with #include <vector>. Same thing for the rest of the standard library: whatever it is that you want to use, find out which header declares it and #include that header.
using namespace std; doesn't define any names for you. It tells the compiler to pretend that any names that have been defined in the namespace std are also defined in the scope where using namespace std; occurs. So that means that instead of writing std::cout you can write cout, and the compiler will figure out that you meant std::cout. Unless, of course, you've written something yourself with the name cout (or any other name that's in std and declared in a header that you've #included), in which case that using declaration makes the use of the name ambiguous. There is no good reason to write using namespace std;. Just use the right names for things: std::cout is clear and unambiguous.
Where is cin and cout actually declared and defined? Is it in #include<iostream> or in namespace std?
It's not or. cin and cout are declared in the iostream header file within the namespace std.
If in #include< iostream> why should we use using namespace std?
You shouldn't. Either fully qualify the global variables like std::cin or std::cout. There's a number of reasons why you shouldn't use using namespace std; (at least in header files).
If in namespace std why should we use #include<iostream>?
Because you need the declarations to compile your code.
iostream is part of the standard library, here is what the "iostream.h" file would look like if you were to implement it yourself:
namespace std{
// code about cin
extern ostream cin;
// code about cout
extern ostream cout;
}
(see c++ STL cout source code)
Where is cin and cout actually declared and defined? Is it in #include <iostream> or in namespace std?
So cin/cout are declared and define in the standard library under the
namespace std. This means that if you want to use it in your code you can do :
int main()
{
std::cout << "Hello";
}
If in #include<iostream> why should we use using namespace std?
You don't need using namespace std, you could call std::cout everywhere instead of cout, but you can see how this can make your code verbose and annoying to type.
using namespace std in your whole file is actually discouraged as it could have unintended effect, usually you could use only
using std::cout;
using std::cin;
where needed.
The reason the using is needed (or the need for explicitly writing std:cout , is imagine you have the following code:
#include <iostream>
namespace mycoolnamespace
{
class foo {
public:
foo& operator<< (const std::string& echo)
{
// do stuff
}
};
foo cout; // created a variable called cout
}
int main()
{
cout << "Hello";
// ^^^^ compiler can't know if you meant to use std::cout or mycoolnamespace::cout here!
// Potential fix:
std::cout << "Hello"
}
If in namespace std why should we use #include<iostream>?
By default not all function/classes from the standard library are included in your program, otherwise a simple "Hello world" program would give a lot of work to the compiler since it would need to parse all the existing classes/functions in the entire standard library. #include<iostream> tells the compiler that you need the functions/classes available in the standard library's iostream 'file'
Basically, I am working with some provided header files with the following format:
#include <iostream>
using namespace std;
class bar
{
public:
void printSomething(void)
{
cout << "This is an example." << endl;
}
}
My question is, since I can't modify the provided header, how do I strip the std namespace in my files and go back to the default global namespace? I have tried "using namespace ::;" and "using namespace ;", but the the compiler isn't happy with either of those. Any ideas on how to force a clean slate with namespaces?
You can't. That's why the using namespace clause is so evul. You could include those headers inside another namespace though:
namespace bleh {
#include "library_that_uses_evul_using_namespace.h"
}
That will pollute only the bleh namespace.
You can't get rid of a "using namespace". You can have multiple "using namespace " statements and they are additive.
However, you can wrap the malicious header into a namespace of it's own:
namespace Crap
{
#include "maliciousHeader.h"
}
That way the "using namespace std" only applies to the namespace Crap. I'd recommend putting the above code into another header which is the header that you actually include in your program.
I am taking a programming class in school and I wanted to start doing some c++ programming out of class. My school using Microsoft Visual C++ 6.0 (which is from 1998) so it still uses <iostream.h> rather than <iostream> and using namespace std. When I started working, I couldn't figure out how and when to use using namespace std and when to just use things like std::cout<<"Hello World!"<<'\n'; (for example) as well as it's limits and other uses for the namespace keyword. In particular, if I want to make a program with iostream and iomanip, do I have to state "using namespace std" twice, or is there something different that I would have to use as well, or can I just do the same thing as I did with iostream? I tried googling it but I didn't really understand anything. Thanks in advance for the help.
Ok, handful of things there, but it is manageable.
First off, the difference between:
using namespace std;
...
cout << "Something" << endl;
And using
std::cout << "Something" << std::endl;
Is simply a matter of scope. Scope is just a fancy way of saying how the compiler recognizes names of variables and functions, among other things. A namespace does nothing more than add an extra layer of scope onto all variables within that namespace. When you type using namespace std, you are taking everything inside of the namespace std and moving it to the global scope, so that you can use the shorter cout instead of the more fully-qualified std::cout.
One thing to understand about namespaces is that they stretch across files. Both <iostream> and <iomanip> use the namespace std. Therefore, if you include both, then the declaration of using namespace std will operate on both files, and all symbols in both files will be moved to the global scope of your program (or a function's scope, if you used it inside a function).
There are going to be people who tell you "don't use using namespace std!!!!", but they rarely tell you why. Lets say that I have the following program, where all I am trying to do is define two integers and print them out:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int cout = 0;
int endl = 1;
cout << cout << endl << endl; // The compiler WILL freak out at this :)
return 0;
}
When I use using namespace std, I am opening the door for naming collisions. If I (by random chance), have named a variable to be the same thing as what was defined in a header, then your program will break, and you will have a tough time figuring out why.
I can write the same program as before (but get it to work) by not using the statement using namespace std:
#include <iostream>
int main(int argc, char** argv) {
int cout = 0;
int endl = 1;
std::cout << cout << endl << std::endl; // Compiler is happy, so I'm happy :)
return 0;
}
Hopefully this has clarified a few things.
If you use the header names without the .h, then the stuff declared/defined in it will be in the std namespace. You only have to use using namespace std; once in the scope where you want stuff imported in order to get everything; more than one using namespace std; doesn't help anything.
I'd recommend against using namespace std; in general, though. I prefer to say, for example, using std::cout; instead, in order to keep names in std from conflicting with mine.
For example:
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
int left = 1, right = 2;
cout << left << " to " << right << "\n";
}
may cause mysterious issues, because left and right exist in the std namespace (as IO manipulators), and they get imported if you lazily say using namespace std;. If you meant to actually use the IO manipulators rather than output the variables, you may be a bit disappointed. But the intent isn't obvious either way. Maybe you just forgot you have ints named left and right.
Instead, if you say
#include <iostream>
#include <iomanip>
int main()
{
using std::cout;
int left = 1, right = 2;
cout << left << " to " << right << "\n";
}
or
#include <iostream>
#include <iomanip>
int main()
{
int left = 1, right = 2;
std::cout << left << " to " << right << "\n";
}
everything works as expected. Plus, you get to see what you're actually using (which, in this case, includes nothing from <iomanip>), so it's easier to keep your includes trimmed down to just what you need.
Here is a good link that describes namespaces and how they work.
Both methods are correct, that is, you can either introduce a namespace with the "using" statement or you can qualify all the members of the namespace. Its a matter of coding style. I prefer qualifying with namespaces because it makes it clear to the reader in which namespace the function / class is defined.
Also, you do not have to introduce a namespace twice if you are including multiple files. One using statement is enough.
Good question, Ryan. What using namespace does is importing all symbols from a given namespace (scope) into the scope where it was used. For example, you can do the following:
namespace A {
struct foo {};
}
namespace B {
using namespace A;
struct bar : foo {};
}
In the above examples, all symbols in namespace A become visible in namespace B, like they were declared there.
This import has affect only for a given translation unit. So, for example, when in your implementation file (i.e. .cpp) you do using namespace std;, you basically import all symbols from std namespace into a global scope.
You can also import certain symbols rather than everything, for example:
using std::cout;
using std::endl;
You can do that in global scope, namespace scope or function scope, like this:
int main ()
{
using namespace std;
}
It is up to a programmer to decide when to use fully qualified names and when to use using keyword. Usually, it is a very bad taste to put using into a header files. Professional C++ programmers almost never do that, unless that is necessary to work around some issue or they are 100% sure it will not mess up type resolution for whoever use that header.
Inside the source file, however (nobody includes source files), it is OK to do any sort of using statements as long as there are no conflicting names in different namespaces. It is only a matter of taste. For example, if there are tons of symbols from different namespaces being used all over the code, I'd prefer at least some hints as for where they are actully declared. But everyone is familiar with STL, so using namespace std; should never do any harm.
There also could be some long namespaces, and namespace aliasing comes handy in those cases. For example, there is a Boost.Filesystem library that puts all of its symbols in boost::filesystem namespace. Using that namespace would be too much, so people usually do something like this:
namespace fs = boost::filesystem;
fs::foo ();
fs::bar ();
Also, it is almost OK to use namespace aliasing in headers, like this:
namespace MyLib {
namespace fs = boost::filesystem;
}
.. and benefit from less typing. What happens is that users that will use this header, will not import the whole filesystem library by saying using namespace MyLib;. But then, they will import "fs" namespace from your library that could conflict with something else. So it is better not to do it, but if you want it too badly, it is better than saying using namespace boost::filesystem there.
So getting back to your question. If you write a library using C++ I/O streams, it is better not to have any using statements in headers, and I'd go with using namespace std; in every cpp file. For example:
somefile.hpp:
namespace mylib {
class myfile : public std::fstream {
public:
myfile (const char *path);
// ...
};
}
somefile.cpp:
#include "somefile.hpp"
using namespace std;
using namespace mylib;
myfile::myfile (const char *path) : fstream (path)
{
// ...
}
Specific to using namespace std
You really shouldn't ever use it in a header file. By doing so, you've imported the entire 'std' into the global namespace for anyone who includes your header file, or for anyone else that includes a file that includes your file.
Using it inside a .cpp file, that's personal preference. I typically do not import the entire std into the global namespace, but there doesn't appear to be any harm in doing it yourself, to save a bit of typing.
for using cout, I need to specify both:
#include<iostream>
and
using namespace std;
Where is cout defined? in iostream, correct? So, it is that iostream itself is there in namespace std?
What is the meaning of both the statements with respect to using cout?
I am confused why we need to include them both.
iostream is the name of the file where cout is defined.
On the other hand, std is a namespace, equivalent (in some sense) to java's package.
cout is an instance defined in the iostream file, inside the std namespace.
There could exist another cout instance, in another namespace. So to indicate that you want to use the cout instance from the std namespace, you should write
std::cout, indicating the scope.
std::cout<<"Hello world"<<std::endl;
To avoid the std:: everywhere, you can use the using clause.
cout<<"Hello world"<<endl;
They are two different things. One indicates scope, the other does the actual inclusion of cout.
In response to your comment
Imagine that in iostream two instances named cout exist, in different namespaces
namespace std{
ostream cout;
}
namespace other{
float cout;//instance of another type.
}
After including <iostream>, you'd still need to specify the namespace. The #include statement doesnt say "Hey, use the cout in std::". Thats what using is for, to specify the scope
If your C++ implementation uses C style header files (many do) then there is a file that contains something similar to:
#include ... // bunches of other things included
namespace std {
... // various things
extern istream cin;
extern ostream cout;
extern ostream cerr;
... // various other things
}
std is the namespace that the C++ standard says most of the standard things should reside in. This is to keep from overpopulating the global namespace, which could cause you difficulty in coming up with names for your own classes, variables, and functions which aren't already used as names for standard things.
By saying
using namespace std;
you are telling the compiler that you want it to search in the namespace std in addition to the global namespace when looking up names.
If the compiler sees the source line:
return foo();
somewhere after the using namespace std; line it will look for foo in various different namespaces (similar to scopes) until it finds a foo that meets the requirements of that line. It searches namespaces in a certain order. First it looks in the local scope (which is really an unnamed namespace), then the next most local scope until over and over until outside of a function, then at the enclosing object's named things (methods, in this case), and then at global names (functions, in this case unless you've been silly and overloaded () which I'm ignoring), and then at the std namespace if you've used the using namespace std; line. I may have the last two in the wrong order (std may be searched before global), but you should avoid writing code that depends on that.
cout is logically defined within iostream. By logically, I mean it may actually be in the file iostream or it may be in some file included from iostream. Either way, including iostream is the correct way to get the definition of cout.
All symbols in iostream are in the namespace std. To make use the the cout symbol, you must tell the compiler how to find it (i.e. what namespace). You have a couple of choices:
// explicit
std::cout << std::endl;
// import one symbol into your namespace (other symbols must still be explicit)
using std::cout;
cout << std::endl;
// import the entire namespace
using namespace std;
cout << endl;
// shorten the namespace (not that interesting for standard, but can be useful
// for long namespace names)
namespace s = std;
s::cout << s::endl;
The #include <iostream> references the header file that defines cout. If you're going to use cout, then you will always need the include.
You do not need to using namespace std;. That's simply allows you to use the shorthand cout and endl and the like, rather than std::cout and std::endl where the namespace is explicit. Personally I prefer not to use using namespace ... since it requires me to be explicit in my meaning, though it is admittedly more verbose.