I have a C++ code that uses endl, vector, complex, and cout occasionally without any namespace qualification. When compiling with GCC 4.9, I get errors like this one:
bfm.h:454:4: error: 'complex' does not name a type
complex<double> inner(Fermion_t x,Fermion_t y);
^
In the very same file, there are lines with an std:: qualifier:
std::complex<Float> dot(Fermion_t x_t, Fermion_t y_t,int sx,int sy);
Throughout the codebase, I saw the following template specializations used
std::complex<double>
std::complex<cFloat>
complex<Float>
complex<double>
complex<T>
complex<S>.
Neither for the regular express struct\s+complex nor class\s+complex I managed to find something in the codebase or the codebase of the base library. Therefore I assume that it indeed is the standard library complex type.
There are a couple of using namespace std scattered around in various header files, but not all of them.
I tried compiling this codebase with GCC 4.9 and Clang 3.7. Both give similar errors about the missing type. Is there some possibility that this has worked with an older version of GCC? I have tried to insert std:: at all the needed points but I have the impression that I do something wrong if I cannot just compile the source checkout that is meant for this type of computer.
you can use selective using... declarations or type aliasing to bring in only the std:: members you need. Like:
using std::complex;
using std::cout;
using std::endl;
cout << "Hello world" << endl; // works
complex<float> x; // works
fstream y; // compile error, no namespace qualification, no using declaration
std::fstream z; // OK
Ah, yes, maybe not that evident, so perhaps worth mentioning. You now that std::endl? Well, it's a stream manipulator, a function in fact.
Which means one can bring in the current block function members from other namespaces as well.
Like:
#include <cmath>
#include <cstdlib>
inline void dummy(float x) {
float y=fabs(x); // Na'a.., fabs is imported into std namespace by <cmath>
using std::itoa; // same is itoa, but we'll be using it
char buff[128];
itoa(42, buff, 10); // OK
}
Related
I'm playing around with my coding style. I used to explicitly prefix every library call with std:: but I'm switching over to using declarations like this:
using std::count;
using std::vector;
One thing I've noticed over the past few days is that sometimes if I forget a using declaration -- using std::vector; is a good example -- I get reams of compiler errors. However, if I neglect to namespace delcare an algorithm such as using std::count; my code compiles just fine.
Does this have to do with the difference with classes and free functions? On all the reference sites, both count(first, last, value) and vector are prefixed with std:: so I would expect them to behave the same.
Or does it have to do with other functions in the global namespace? I notice std::max also seems to require a namespace declaration, perhaps it defined in a default-included Apple/glibc/LLVM file and thus there is a conflict if I used it sans namespace declaration?
I am using Apple LLVM 7.0.2. on El Capitan.
EDIT: Show us the code
#include <algorithm>
#include <vector>
using std::count;
using std::vector;
int main() {
vector<int> v = { 1, 2, 3, 4 };
return count(begin(v), end(v), 3);
}
As T.C. (almost) said, the magic incantation is ADL, which stands for "argument-dependent lookup". When a function is called with an argument whose type is defined in a namespace, the compiler looks for the function in that same namespace. Makes, sense, right?
I am developing a project which works with multiple arithmetic types. So I made a header, where the minimal requirements for a user defined arithmetic type are defined:
user_defined_arithmetic.h :
typedef double ArithmeticF; // The user chooses what type he
// wants to use to represent a real number
namespace arithmetic // and defines the functions related to that type
{
const ArithmeticF sin(const ArithmeticF& x);
const ArithmeticF cos(const ArithmeticF& x);
const ArithmeticF tan(const ArithmeticF& x);
...
}
What is troubling me is that when I use code like this:
#include "user_defined_arithmetic.h"
void some_function()
{
using namespace arithmetic;
ArithmeticF lala(3);
sin(lala);
}
I get a compiler error:
error: call of overloaded 'sin(ArithmeticF&)' is ambiguous
candidates are:
double sin(double)
const ArithmeticF arithmetic::sin(const ArithmeticF&)
I have never used the <math.h> header, only the <cmath>. I have never used the using namespace std in a header file.
I am using gcc 4.6.*. I checked what is the header containing the ambiguous declaration and it turns out to be:
mathcalls.h :
Prototype declarations for math functions; helper file for <math.h>.
...
I know, that <cmath> includes <math.h>, but it should shield the declarations by the std namespace. I dig into the <cmath> header and find:
cmath.h :
...
#include <math.h>
...
// Get rid of those macros defined in <math.h> in lieu of real functions.
#undef abs
#undef div
#undef acos
...
namespace std _GLIBCXX_VISIBILITY(default)
{
...
So the namespace std begins after the #include <math.h>. Is there something wrong here, or did I misunderstand something?
Implementations of the C++ standard library are permitted to declare C library functions in the global namespace as well as in std. Some would call this a mistake, since (as you've found) the namespace pollution can cause conflicts with your own names. However, that's the way it is, so we must live with it. You'll just have to qualify your name as arithmetic::sin.
In the words of the standard (C++11 17.6.1.2/4):
In the C++ standard library, however, the declarations (except for
names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is
unspecified whether these names are first declared within the global namespace scope and are then injected
into namespace std by explicit using-declarations (7.3.3).
If you really wanted to, you could always write a little wrapper around cmath, along the lines of:
//stdmath.cpp
#include <cmath>
namespace stdmath
{
double sin(double x)
{
return std::sin(x);
}
}
//stdmath.hpp
#ifndef STDMATH_HPP
#define STDMATH_HPP
namespace stdmath {
double sin(double);
}
#endif
//uses_stdmath.cpp
#include <iostream>
#include "stdmath.hpp"
double sin(double x)
{
return 1.0;
}
int main()
{
std::cout << stdmath::sin(1) << std::endl;
std::cout << sin(1) << std::endl;
}
I suppose there could be some overhead from the additional function call, depending on how clever the compiler is.
This is just a humble attempt to start solving this problem. (Suggestions are welcomed.)
I have been dealing with this problem a long time. A case were the problem is very obvious is this case:
#include<cmath>
#include<iostream>
namespace mylib{
std::string exp(double x){return "mylib::exp";}
}
int main(){
std::cout << std::exp(1.) << std::endl; // works
std::cout << mylib::exp(1.) << std::endl; // works
using namespace mylib;
std::cout << exp(1.) << std::endl; //doesn't works!, "ambiguous" call
return 0;
}
This is in my opinion is an annoying bug or at the least an very unfortunate situation. (At least in GCC, and clang --using GCC library-- in Linux.)
Lately I gave it another shot to the problem. By looking at the cmath (of GCC) it seems that the header is there simply to overload the C-functions and screws up the namespace in the process.
namespace std{
#include<math.h>
}
//instead of #include<cmath>
With it this works
using namespace mylib;
std::cout << exp(1.) << std::endl; //now works.
I am almost sure that this is not exactly equivalent to #include<cmath> but most functions seem to work.
Worst of all is that eventually some dependence library will eventually will #inclulde<cmath>. For that I couldn't find a solution yet.
NOTE: Needless to say this doesn't work at all
namespace std{
#include<cmath> // compile errors
}
Since the namespace std already has the c++ libraries that contain the function definitions(if i am right), then why do we include header files on top of it??. Since namespace std includes the c++ standard libraries, I don't see a reason to include the declarations of it separately.
When you do #include <iostream> it causes a set of classes and other things to be included in your source file. For iostream, and most of the standard library headers, they place these things in a namespace named std.
So the code for #include <iostream> looks something like this:
namespace std {
class cin { ... };
class cout { ... };
class cerr { ... };
class clog { ... };
...
}
So at this point, you could write a program that looks like:
#include <iostream>
int main() {
std::cout << "hello\n";
return 0;
}
Now, some people feel that std::cout is too verbose. So they do:
#include <iostream>
using namespace std;
int main() {
cout << "hello\n";
return 0;
}
Personally, I'd recommend against this, and if you really feel that std::cout is too verbose, then I'd suggest that you use a smaller using statement.
#include <iostream>
using std::cout;
int main() {
cout << "hello\n";
return 0;
}
If you're wondering why I would recommend against using namespace std, then I would forward you to the following two other posts on stackoverflow:
C++ Distance Function Keeps Returning -1
Why is "using namespace std" considered bad practice?
The compiler itself does not have the definitions of the things that are in any namespace (whether it is std or some other namespace). That is the role of source files and header files.
What using namespace std; tells the compiler is that "If you can't find some name in the current namespace, go look in the std namespace as well".
What #include <iostream> tells the compiler is that you want the contents of the header called iostream to be included in your sources. This will provide the compiler with code to do cin, cout and a lot of other related functionality. The content of this file is declared like namespace std { ... all the stuff goes here ... }.
The usage of namespace allows someone else, working in namespace math; to not have to worry about "Hmm, what do I do now, I need a counter for number of entrances, let's call it cin - but hang on, is that ever used anywhere?".
This may not be the greatest of examples, but in large projects, it gets increasingly hard to keep track of things and what names they have. And C++ is a language intended for large projects of millions of lines of code - and now it starts getting hard to remember if you've used a particular name or not. Namespaces make sure that you don't have to worry about it outside of a particular namespace.
(Oh, and in my code, I tend to not use using namespace std;, but write std::cout << "Hello, World!" << std::endl; - this helps to make it clear that the cout I'm using here is the std one, and not something else. This is particularly useful when you have several namespaces with similar things, like in my own compiler, where I have my compiler with it's functionality, the std namespace providing some things, and llvm compiler things - if I were to stick using namespace llvm; at the beginning of the code, it would be very hard to track whether Type* p = ...; is from LLVM or some part of my own code.)
...why do we include header files on top of it???
Yes, there is some big confusion here.
Namespaces
Namespaces are a method to categorize or group together, symbols such as function names.
Namespaces are design to prevent name conflicts between different software components, such as libraries.
Functions that are a part of the standard language, are grouped under the namespace std.
The C++ language provides statements to reduce the amount of typing when using namespaces. One of these is the using statement.
Header (include) Files
When you write a program, the compiler is not required to automatically include all the symbol definitions, such a function declarations. You need to tell it which functions you plan on using.
For example, I could write a program without using the sort or advance functions from the algorithm group. Therefore I would not include the header file algorithm.
The C++ language is designed to be "use what you need", in other words, we can create small programs by only including the functions we need.
Other Platforms
By the way, there are many other platforms out there than the one you are using.
Some platforms need to fit in small memory areas and may not have a keyboard or display (such as embedded controllers).
So remember, C++ was defined to support platforms from the small and constrained to the large and virtually unconstrained system.
Thus the requirement to "include only what you need" theme.
Summary
In summary, since the C++ languages doesn't automatically, magically, provide the definitions of the entire library, including the template library, you need to tell the compiler which groups of functions you want to use. This allows for quicker compilations since only the required header files are specified.
Note: Some shops and library supplies like to use the Monolith include system. This means that they have one include file that includes their entire library, whether you use one function or many. The windows.h is a classic example. One detriment is that when one header file is changed, everything needs to be rebuilt. With separated include files, only the components that include the changed header file need to be rebuilt.
Use of preprocessor directive #include is as old as c++ itself. And its not going away any sooner.In C++ namespace Doesn't import anything into your program, it just defines the scope of your particular header file's function.So, both are required. Click hereto understand why use namespace.
Your question is: namespace std has all the definitions of functions/classes of iostream library. So simply using using namespace std is enough to call or use cout or all other functionalities of iostream library. Why do we have to use line #include <iostream>? It seems redundant.
Roughly we can think that iostream library has two files: header and implementation/source file. These two files have a namespace called std. The header file only contains the declarations or forward declarations of classes or functions or variables that iostream library is going to use and these declarations or forward declarations are under the std namespace. The implementation file contains the actual implementations of the classes or functions or variables and these implementations are under the std namespace; this file is also called the source file.
So if you only use using namespace std without #include <iostream> in your main.cpp file compiler will search std namespace in your main.cpp file, but it is not here. You will get compiler error.
Now if you include this #include <iostream> line in your main.cpp, preprocessor will go iostream's header file and copy the std namespace along with its code into our main.cpp. And linker will link the precompiled(as iostream is a SLT so it comes with compiler with prebuilt) source/implementation file of iostream to your main.cpp. Now to use functions or variables of iostream that sit under std namespace in main.cpp we have to use scope resolution operator(::) to tell the compiler that cout, cin and other functionalities of iostream sit at std namespace. Thus we simply write like this: std::cin, and std::cout.
Now typing std:: seems redundant to some people so they tell the compiler by using this using namespace std "Hey compiler, if you don't find any variables/functions/classes in global/current namespace go look in the std namespace." Though this is not the best practice but that is another topic to discuss. Therefore your assumption that std namespace contains all the definitions of all SLT's functions/classes/variables of C++ is not correct in most cases, but std namespace only contains the declaration from STL is the correct assumption.
Here is a dummy implementation how iostream libray is added to our code files:
iostream.h:
// This is header file that only contains the
// functions declarations.
namespace std_dum
{
int add(int x, int y);
int mult(int x, int y);
}
iostream_dum.cpp:
// This is source file of iostream_dum.h header
// which contains the implementation of functions.
#include "iostream_dum.h"
namespace std_dum
{
int add(int x, int y)
{
return x + y;
}
int mult(int x, int y)
{
return x * y;
}
}
main.cpp :
#include <iostream>
#include "iostream_dum.h"
int main()
{
std::cout << std_dum::add(100, 200) << '\n';
std::cout << std_dum::mult(100, 200) << '\n';
return 0;
}
To see what happens to our main.cpp file after preprocessing run this command: g++ -E main.cpp iostream_dum.cpp.
Here is roughly our main.cpp looks like:
namespace std_dum
{
int add(int x, int y);
int mult(int x, int y);
}
int main()
{
std::cout << std_dum::add(100, 200) << '\n';
std::cout << std_dum::mult(100, 200) << '\n';
return 0;
}
namespace std_dum
{
int add(int x, int y)
{
return x + y;
}
int mult(int x, int y)
{
return x * y;
}
}
For the sake of clarity, I discarded all the codes that the preprocessor copied from #include <iostream>.
Now it should be pretty clear.
In C, if I use #include "someFile.h", the preprocessor does a textual import, meaning that the contents of someFile.h are "copy and pasted" onto the #include line. In C++, there is the using directive. Does this work in a similar way to the #include, ie: a textual import of the namespace?
using namespace std; // are the contents of std physically inserted on this line?
If this is not the case, then how is the using directive implemented`.
The using namespace X will simply tell the compiler "when looking to find a name, look in X as well as the current namespace". It does not "import" anything. There are a lot of different ways you could actually implement this in a compiler, but the effect is "all the symbols in X appear as if they are available in the current namespace".
Or put another way, it would appear as if the compiler adds X:: in front of symbols when searching for symbols (as well as searching for the name itself without namespace).
[It gets rather complicated, and I generally avoid it, if you have a symbol X::a and local value a, or you use using namespace Y as well, and there is a further symbol Y::a. I'm sure the C++ standard DOES say which is used, but it's VERY easy to confuse yourself and others by using such constructs.]
In general, I use explicit namespace qualifiers on "everything", so I rarely use using namespace ... at all in my own code.
No, it does not. It means that you can, from this line on, use classes and functions from std namespace without std:: prefix. It's not an alternative to #include. Sadly, #include is still here in C++.
Example:
#include <iostream>
int main() {
std::cout << "Hello "; // No `std::` would give compile error!
using namespace std;
cout << "world!\n"; // Now it's okay to use just `cout`.
return 0;
}
Nothing is "imported" into the file by a using directive. All it does is to provide shorter ways to write symbols that already exist in a namespace. For example, the following will generally not compile if it is the first two lines of a file:
#include <string>
static const string s("123");
The <string> header defines std::string, but string is not the same thing. You haven't defined string as a type, so this is an error.
The next code snippet (at the top of a different file) will compile, because when you write using namespace std, you are telling the compiler that string is an acceptable way to write std::string:
#include <string>
using namespace std;
static const string s("123");
But the following will not generally compile when it appears at the top of a file:
using namespace std;
static const string s("123");
and neither will this:
using namespace std;
static const std::string s("123");
That's because using namespace doesn't actually define any new symbols; it required some other code (such as the code found in the <string> header) to define those symbols.
By the way, many people will wisely tell you not to write using namespace std in any code. You can program very well in C++ without ever writing using namespace for any namespace. But that is the topic of another question that is answered at Why is "using namespace std" considered bad practice?
No, #include still works exactly the same in C++.
To understand using, you first need to understand namespaces. These are a way of avoiding the symbol conflicts which happen in large C projects, where it becomes hard to guarantee, for example, that two third-party libraries don't define functions with the same name. In principle everyone can choose a unique prefix, but I've encountered genuine problems with non-static C linker symbols in real projects (I'm looking at you, Oracle).
So, namespace allows you to group things, including whole libraries, including the standard library. It both avoids linker conflicts, and avoids ambiguity about which version of a function you're getting.
For example, let's create a geometry library:
// geo.hpp
struct vector;
struct matrix;
int transform(matrix const &m, vector &v); // v -> m . v
and use some STL headers too:
// vector
template <typename T, typename Alloc = std::allocator<T>> vector;
// algorithm
template <typename Input, typename Output, typename Unary>
void transform(Input, Input, Output, Unary);
But now, if we use all three headers in the same program, we have two types called vector, two functions called transform (ok, one function and a function template), and it's hard to be sure the compiler gets the right one each time. Further, it's hard to tell the compiler which we want if it can't guess.
So, we fix all our headers to put their symbols in namespaces:
// geo.hpp
namespace geo {
struct vector;
struct matrix;
int transform(matrix const &m, vector &v); // v -> m . v
}
and use some STL headers too:
// vector
namespace std {
template <typename T, typename Alloc = std::allocator<T>> vector;
}
// algorithm
namespace std {
template <typename Input, typename Output, typename Unary>
void transform(Input, Input, Output, Unary);
}
and our program can distinguish them easily:
#include "geo.hpp"
#include <algorithm>
#include <vector>
geo::vector origin = {0,0,0};
typedef std::vector<geo::vector> path;
void transform_path(geo::matrix const &m, path &p) {
std::transform(p.begin(), p.end(), p.begin(),
[&m](geo::vector &v) -> void { geo::transform(m,v); }
);
}
Now that you understand namespaces, you can also see that names can get pretty long. So, to save typing out the fully-qualified name everywhere, the using directive allows you to inject individual names, or a whole namespace, into the current scope.
For example, we could replace the lambda expression in transform_path like so:
#include <functional>
void transform_path(geo::matrix const &m, path &p) {
using std::transform; // one function
using namespace std::placeholders; // an entire (nested) namespace
transform(p.begin(), p.end(), p.begin(),
std::bind(geo::transform, m, _1));
// this ^ came from the
// placeholders namespace
// ^ note we don't have to qualify std::transform any more
}
and that only affects those symbols inside the scope of that function. If another function chooses to inject the geo::transform instead, we don't get the conflict back.
This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare
using namespace std;
in C++ programs?
Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive.
However,
using namespace std;
is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like
using std::string;
Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::
Technically, you might be required to use using (for whole namespaces or individual names) to be able to use Argument Dependent Lookup.
Consider the two following functions that use swap().
#include <iostream>
#include <algorithm>
namespace zzz
{
struct X {};
void swap(zzz::X&, zzz::X&)
{
std::cout << "Swapping X\n";
}
}
template <class T>
void dumb_swap(T& a, T& b)
{
std::cout << "dumb_swap\n";
std::swap(a, b);
}
template <class T>
void smart_swap(T& a, T& b)
{
std::cout << "smart_swap\n";
using std::swap;
swap(a, b);
}
int main()
{
zzz::X a, b;
dumb_swap(a, b);
smart_swap(a, b);
int i, j;
dumb_swap(i, j);
smart_swap(i, j);
}
dumb_swap always calls std::swap - even though we'd rather prefer using zzz::swap for zzz::X objects.
smart_swap makes std::swap visible as a fall-back choice (e.g when called with ints), but since it doesn't fully qualify the name, zzz::swap will be used through ADL for zzz::X.
Subjectively, what forces me to use using namespace std; is writing code that uses all kinds of standard function objects, etc.
//copy numbers larger than 1 from stdin to stdout
remove_copy_if(
std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, "\n"),
std::bind2nd(std::less_equal<int>(), 0)
);
IMO, in code like this std:: just makes for line noise.
I wouldn't find using namespace std; a heinous crime in such cases, if it is used in the implementation file (but it can be even restricted to function scope, as in the swap example).
Definitely don't put the using statement in the header files. The reason is that this pollutes the namespace for other headers, which might be included after the offending one, potentially leading to errors in other headers which might not be under your control. (It also adds the surprise factor: people including the file might not be expecting all kinds of names to be visible.)
The ability to refer to members in the std namespace without the need to refer to std::member explicitly. For example:
#include <iostream>
using namespace std;
...
cout << "Hi" << endl;
vs.
#include <iostream>
...
std::cout << "Hi" << std::endl;
You should definitely not say:
using namespace std;
in your C++ headers, because that beats the whole point of using namespaces (doing that would constitute "namespace pollution"). Some useful resources on this topic are the following:
1) stackoverflow thread on Standard convention for using “std”
2) an article by Herb Sutter on Migrating to Namespaces
3) FAQ 27.5 from Marshall Cline's C++ Faq lite.
First of all, this is not required in C - C does not have namespaces. In C++, anything in the std namespace which includes most of the standard library. If you don't do this you have to access the members of the namespace explicitly like so:
std::cout << "I am accessing stdout" << std::endl;
Firstly, the using directive is never required in C since C does not support namespaces at all.
The using directive is never actually required in C++ since any of the items found in the namespace can be accessed directly by prefixing them with std:: instead. So, for example:
using namespace std;
string myString;
is equivalent to:
std::string myString;
Whether or not you choose to use it is a matter of preference, but exposing the entire std namespace to save a few keystrokes is generally considered bad form. An alternative method which only exposes particular items in the namespace is as follows:
using std::string;
string myString;
This allows you to expose only the items in the std namespace that you particularly need, without the risk of unintentionally exposing something you didn't intend to.
Namespaces are a way of wrapping code to avoid confusion and names from conflicting. For example:
File common1.h:
namespace intutils
{
int addNumbers(int a, int b)
{
return a + b;
}
}
Usage file:
#include "common1.h"
int main()
{
int five = 0;
five = addNumbers(2, 3); // Will fail to compile since the function is in a different namespace.
five = intutils::addNumbers(2, 3); // Will compile since you have made explicit which namespace the function is contained within.
using namespace intutils;
five = addNumbers(2, 3); // Will compile because the previous line tells the compiler that if in doubt it should check the "intutils" namespace.
}
So, when you write using namespace std all you are doing is telling the compiler that if in doubt it should look in the std namespace for functions, etc., which it can't find definitions for. This is commonly used in example (and production) code simply because it makes typing common functions, etc. like cout is quicker than having to fully qualify each one as std::cout.
You never have to declare using namespace std; using it is is bad practice and you should use std:: if you don't want to type std:: always you could do something like this in some cases:
using std::cout;
By using std:: you can also tell which part of your program uses the standard library and which doesn't. Which is even more important that there might be conflicts with other functions which get included.
Rgds
Layne
All the files in the C++ standard library declare all of its entities within the std namespace.
e.g: To use cin,cout defined in iostream
Alternatives:
using std::cout;
using std::endl;
cout << "Hello" << endl;
std::cout << "Hello" << std::endl;
Nothing requires you to do -- unless you are implementer of C++ Standard Library and you want to avoid code duplication when declaring header files in both "new" and "old" style:
// cstdio
namespace std
{
// ...
int printf(const char* ...);
// ...
}
.
// stdio.h
#include <cstdio>
using namespace std;
Well, of course example is somewhat contrived (you could equally well use plain <stdio.h> and put it all in std in <cstdio>), but Bjarne Stroustrup shows this example in his The C++ Programming Language.
It's used whenever you're using something that is declared within a namespace. The C++ standard library is declared within the namespace std. Therefore you have to do
using namespace std;
unless you want to specify the namespace when calling functions within another namespace, like so:
std::cout << "cout is declared within the namespace std";
You can read more about it at http://www.cplusplus.com/doc/tutorial/namespaces/.