Using the .h extension - c++

I am a student who is learning C++. I have gone through tutorials in the Internet. All of them do not use a .h extension after some include files, such as
#include <iostream>
But my C++ lecturer says that I have to include a .h extension after iostream, such as:
#include <iostream.h>
My book "The Waite Group's Object Oriented Programming In Turbo C++" written by Robert Lafore also tells me to put a .h extension after iostream. Both my lecturer and the book says there is no need to have the following line of code when using the cout and cin functions.
using namespace std;
When using cout and cin functions, the namespace std is needed, right? If I try to do what the book and lecturer tells, my compiler(g++) gives me errors. The book also says to use
void main()
rather than
int main()
If I follow what the lecturer or the book says, I get errors during compiling. What is happening? I am using g++ on Linux Mint 17 for compiling.

Your lecturer and his book are incorrect/depend on things that were sort of the case 20 years ago.
Before C++ was standardized in 1998, many compilers (or rather: their library implementations) did in fact know a header <iostream.h> in which several symbols that are in the namespace std in standard C++ existed in the global namespace. Which symbols exactly varied from compiler to compiler, as many things did in those days. These headers were not included in the C++ standard of 1998, and not in any after them. Today, recent compilers will outright reject code that attempts to use them.
But that will not convince your lecturer that he was wrong these last 15 years, so here's what you can show him (if you believe that doing so will not make you an enemy for life):
This is a link to the last publicly available draft of the C++11 standard, which is the one you can reasonably expect to be able to use today. Open it, go to page 429 (or search for [headers]), see that <iostream> is listed while <iostream.h> is not.
See at the bottom on page 428 in [contents] that symbols of the standard library are in namespace std:
All library entities except macros, operator new and operator delete are defined within the namespace std or namespaces nested within namespace std. (...)
Additionally, about the main function, go to page 61 (or search for [basic.start.main]) to see that void main is not allowed:
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is imlementation-defined. All implementations shall allow both of the following definitions of main:
int main() { /* ... */ }
and
int main(int argc, char *argv[]) { /* ... */ }
(...)
(Emphasis mine)

This book appears to be very outdated. Get a new one.
Do not write <iostream.h>, <iostream> is correct (same for all standard headers).
Do not use using namespace std;, here is why. Use the fully qualified names like std::cout << "Hello World\n"; instead.
Your main should either be int main () or int main (int argc, char **argv), depending on if you want to handle command line arguments or not.
Also, do not use TurboC++, it is terribly outdated.

According to my knowledge and what my prof told us last time:
You can choose to or not to include with the .h. The .h are usually older versions. Once again the using namespace can be optional for you right now. (Does not means this is a good practice, but as a student many schools allowed it.)
Some books explain with using namespace, some don't.
So what is the difference of using namespace and not using it?
Using cout for example. If you used namespace std at the beginning of your codes. You can simply do this:
cout << "hello" ;
However, if you didn't add the line using namespace std;. You have to write it this way:
std::cout << "hello";
By the way, we always use int main() in school back then when I was in university. I don't think void main() is a good idea.

Related

is namespace std defined in multiple headers

I am trying to understand namespace std. I know what a namespace is. I want to know, is namespace std defined in multiple header files?
I have two sample codes here, and they both compile and run fine. One uses #include<string> and the other uses #include<iostream>. Both use "using namespace std". This tells me that std is defined in both headers, is that right? If so, then when I use both headers in the same code, how will the compiler know which std to use?
CODE 1:
#include <string>
using namespace std;
int main()
{
string test;
test = "hello";
return 0;
}
CODE 2:
#include <iostream>
using namespace std;
int main()
{
string test;
test = "hello";
return 0;
}
A namespace is open; that is, you can add names to it from several separate namespace declarations. For example:
namespace A {
int f();
}
namespace A {
int g();
}
All namespaces with the same name (and in the same scope) are unified to one, so the compiler doesn’t have to choose.
"this tells me that std is defined in both the headers. is that
right?"
The headers include parts of the standard library. Both, iostream and string belong to the standard library, and each of them provides a different set of commands that can be addressed with std::.
The insertion of using namespace resolves the scope, which means that the compiler searches for a function or a command within std::: if it is not found in an inner scope. Therefore, instead of, e.g., writing std::cout << "Hello world" << std::endl; you can simply write cout << "Hello world" << endl; (assuming that iostream is included). This shortens and simplifies the writing of the code, but it can also have disadvantages, which is why using namespace std is generally considered bad practice.
Some headers of the standard library are included indirectly when another header is included. This appears to be the case in your Code2, which compiles although #include<string> is missing.
One cannot rely on such indirect inclusions. More information on this topic can be found here:
Do I have to use #include <string> beside <iostream>?
I know what a namespace is.
Perhaps you do, perhaps not exactly. A namespace is a tool used to prevent naming conflicts. Everything belonging (directly) to a namespace is public, as public identifiers are the only ones that can conflict with code outside the namespace. Unlike a class, there is no encapsulation or data integrity concerns to address; such concerns are relegated to the classes within the namespace.
This open nature of namespaces means that, unlike class definitions, a namespace definition need not be complete. All you need is for (the teams working on) the pieces of the namespace to coordinate their naming schemes. This is why it is typically wrong to add something to someone else's namespace. Since you are not part of the coordination, you could inadvertently introduce a conflict, perhaps quietly introducing undefined behavior, no diagnostic required.
Syntactically, though, you can add to any namespace. This is a useful feature, since traditionally one creates a header file for each class, and namespaces often span more than one class. So it is often desired for a namespace to span multiple header files. How to use namespace across several files? Just use the same namespace name in each namespace definition. A namespace definition is not so much a "definition" as it is a "tour". It is more "this is part of the namespace" than "this is the namespace". The more tours/parts you see, the more complete your view.
On the subject of incomplete views of a namespace, see Can the definition of a namespace span multiple translation units? (Hopefully you guessed "yes".)
I want to know, is namespace std defined in multiple header files?
Yes. The C++ standard dictates dozens of header files that must exist, and implementations are allowed to break those into auxiliary headers. See cppreference.com for a list of the required headers; the ones listed before the "C compatibility headers" section collectively define the std namespace.

What's the relation between libraries and namespaces?

Just started collage and I'm new in the world of programming. So, as I was learning C++ I bumped into a question that wouldn't let me be : "Why do i need to include "using namespace std" in my code to be able to write or read if i already got iostream?" , because I've been told that "cin/cout" are already defind in iostream library, but I noticed that if I write one of these lines alone it will give a compilation error. And ,therefore, what's the relation between iostream and "std" namespace ...Can someone explain , please? Thank you! <3
#include vs using
In simple terms:
#include <iostream> // include the header
int main() {
// now you can use stuff declared in that header
std::cout << "Hello world" << std::endl;
// if you are lazy you can "use" things:
using std::cout;
using std::endl;
cout << "Hello World" << endl;
}
You do not have to write using namespace std;! The cases where it is appropriate to do that are so rare and the cases where it really does great harm are so frequent that as a rule of thumb you can remember: Never use it! For details see here: Why is “using namespace std;” considered bad practice?. It is imporant to realize that the difference between fully qualifying a name, std::cout, and not fully qualifying the name, cout, is not just about typing 5 characters more or less (read on...).
libraries vs namespaces
What's the relation between libraries and namespaces?
The standard library puts everything in the std namespace. Namespaces help to keep things separated. A different library can contain a other_namespace::vector and there will be no confusion with std::vector because we have namespaces.
the really cool stuff
One deeper reason to use namespaces is Argument Dependent Lookup. I will try to explain with a simple example. Suppose you are using a library with some function template that does something with objects of a type you will have to supply:
namespace library {
template<typename T>
void do_something(T& a,T& b){
std::cout << "wrong...\n";
std::swap(a,b); // (1)
std::cout << "correct\n";
using std::swap;
swap(a,b); // (2)
}
}
I takes two objects and swaps them twice. You have to bear with me for second to understand why (1) is wrong and only (2) is correct. For now we have a library function template and to use that we need some type T:
namespace A {
struct foo{};
void swap(foo& a,foo& b) {
std::cout << "A::swap" << "\n";
}
}
Imagine foo is such that we know a better way than std::swap to swap to instances. Actually foo is empty, so to swap two objects we have to do nothing.
Lets recap: There is std::swap that comes with the standard library. Someone wrote a library (called library) we want to use. We want the library code to call A::swap instead of std::swap. The library author doesn't even know that A::swap exists.
Together with above A and library, this code
int main() {
A::foo a,b;
library::do_something(a,b);
}
will print:
wrong...
correct
A::swap
Live Example. What happened? This line:
std::swap(a,b); // (1)
calls std::swap, no doubt. Not what we want. We would like the library code to call our A::swap.
Now this:
using std::swap;
swap(a,b); // (2)
The first line pulls the name swap from std into the scope of the function. In the second line finally ADL kicks in because it says swap not std::swap. ADL in a nutshell is: a and b are from namespace A, so when the compiler searches for all possible swaps it also searches in A. If it finds one in A then it calls that (and if it does not find one in A there is still the swap coming from std). Hence only (2) calls our custom swap.
This can only work with namespaces. The "cool stuff" is that the library author does not need to know anything about your namespace but still their library code will call your function from your namespace if it exists.
I should note that not all code is generic library code. Often you want to write code where you know what happens in each detail, you want to know what functions get called. Often you do not want your code behave differently depending on a specific header being included or not. Hence, lots of code is better off with fully qualifiying function calls: std::foo.
conclusion
I hope that I could convince you that namespaces is not just about typing some characters more or less. using namespace std; for lazyness completly misses the point of namespaces. On the other hand, pulling names into scope via using std::foo; foo(); is
completely fine and enables ADL.
Libraries and namespaces are related by convention.
By convention, the symbols that a library provides to the programmer-user are contained in a namespace. This organizes things, and there are some higher level language features (ADL) that mean code in a namespace behaves differently than code outside of it.
When you type using namespace std; you tell the compiler "when you run into a symbol, also look into std to find if you can determine what it is". It is generally a really really bad idea to do this at "file" scope; doing it within a single short function is usable, but any more than that can lead to really tricky bugs.
The standard, professional way to interact with namespace std is to prefix your symbols with the namespace:
std::cout << "Hello world\n";
rather than
using namespace std;
cout << "Hello world\n";
and definitely never:
using namespace std;
int main() {
cout << "Hello world\n";
}
you can also grab single symbols, which isn't as bad as importing an entire namespace:
using std::cout;
cout << "Hello world\n";
but should also be avoided at "file" scope.
#include <iostream>
this includes the header file named iostream from the system search path. iostream is part of the standard library. By convention (and the C++ standard), the symbols that iostream provides your program with are located within namespace std.
By putting symbols in a namespace, you avoid conflict with your code. There are many, many symbols in std, and if #include <iostream> shoved some unknown number of symbols into your global namespace, you could easily get errors or the wrong function called in unexpected ways.
std::cout and using namespace std; cout and using std::cout are all ways to tell the compiler in what namespace to find the symbol cout.
#include <iostream> includes cout in namespace std; without it, your code is unaware of its existence.
C++ developed from C, and C has a textual inclusion model. #include actually takes the content of the file iostream and copy/pastes it into your file. Your compiler then reads that extended file and finds the symbols in <iostream>.
Because this textual inclusion could shove a LOT of stuff, having it isolated to a namespace prevents problems for you, the programmer.
Recently, C++ has added modules. Modules are an alternative to #include directives, in that it directly grabs symbols from a library and injects it into your code without a huge copy paste.
In modules, namespaces are still not directly connected to the module. You can
import std;
or
import std.iostream;
and that will just import the std library symbols, still in namespace std, into your code. (the C++ standard added modules, but did not modularize the std library yet, so those names above are speculation).
The symbol lookup is not directly connected to the symbol import.
This lets symbol import be done in large chunks, while lookup be done more carefully.
iostream is a library. It's code someone has written for you so you don't have to do it. By adding #include <iostream> you tell the preprocessor to paste in that code. But the functions and structures that are provided by this code might have names that interfere with others. But that isn't a problem because you can just separate them by putting them in a namespace, the STL(which upstream is part of) does this with std(short for standard, pronounced as 'stood'). When something is in a namespace, you must name that namespace to access stuff in that. i.e. std::cout. But sometimes you don't want to have to write std:: every time you want to access something from the STL. That's what using namespace std does for you. That way, you can just type cout. But this is a very bad idea!
Libraries
Libraries have portions of codes pre-written to provide you with functionalities. Could be in the form of functions/overloaded operators etc.
There are two types of libraries:
Standard Libraries e.g. #include <iostream> and the name of library is in angle brackets.
User defined/made e.g. #include "randomLib.h" and the name of library is in double quotes.
Namespaces
When you require multiple libraries for your project. There is possibility that the both may include multiple methods (function definition) with the same name or a single library may use same function names but in different namespaces. Namespaces are there to remove the confusion or ambiguity for the compiler and user.
Lets say lib 1 has namespace abc{ foo(); } and lib 2 has namespace def{ foo(); }
So you will do abc::foo() or def::foo() for you required functionality. Here abc/def is the namespace, :: is called scope resolution operator and foo() is the method you are calling.

Why the c++ function `getline` doesn't need `std::` to be in front of it? [duplicate]

Consider this bit of code:
#include <iostream>
#include <string>
int main()
{
std::string str;
std::cout << "Enter a string: \n";
getline(std::cin, str);
}
Why must I use std:: for string, cin and cout, but not getline()? Is getline() not in the standard library? I'm actually somewhat confused why I can't just write using namespace std; and not have to #include anything in the standard library, too. Thanks in advance!
Re the magic automatic namespace qualification.
It's Andrew Koenig's* fault.
He considered the problem of providing operators for user defined types. And came up with the idea of resolving the function depending on its arguments. E.g. with an argument of type defined in namespace std, the compiler looks (also) in namespace std.
That's called either Koenig lookup or ADL, short for Argument Dependent Lookup.
Re using namespace std;.
For short exploratory programs you not only can, but to save work you should, do this.
However, the standard library defines some identifiers such as distance that are very likely to collide with names you use.
Hence, for more serious code consider whether other means of avoiding verbosity, might be better. Many programmers even maintain that you should not use using namespace std; in serious code. Some Norwegian firms have this as a coding guideline (I don't agree with so absolute a view, but you should know that it's there, and may be a majority view).
At any rate:
Never put a using namespace std; in the global namespace in a header
because that makes name collisions like distance very likely for some code that includes the header.
Why using doesn't make things accessible.
Many programming languages, such as Java and C# and Ada and Modula-2 and UCSD Pascal, just to name some, have language support for separately compiled modules, where a module consists of functions, variables, types, constants, maybe more.
Depending on the language a module may be called a "module" (Modula-2), a "package" (Ada, Java), a "unit" (Pascal), a "class" (Eiffel), so on.
C++ has a much more primitive system of separate compilation, where essentially the compiler proper knows nothing about modules. The preprocessor can drag in text from "headers", which provides a way to get consistent declarations of things. And to easily get those declarations.
But that's all, and the current primitive text inclusion system has a large number problems, most manifestly visible via various compilers' support for so called "precompiled headers" (not part of the C++ standard!).
David Vandevoorde has worked on a module proposal for C++.
Sadly, it wasn't ready for C++11, but maybe it will come later.
*: In a comment David Rodriguez adds that “it is not really Andrew's fault. He only intended ADL for operators, the committee extended that to all functions”.

Which C++ version has #include iostream.h already defined? "didn't have to use std::"

When I took my second programing class this was the version. (long time ago)
My teacher let me take it home to practice it was on 5-7 disk (3.5 floppy) to install.
I believe it's Turbo C++ Professional 2.0
It had templates, projects options and used the standard mini square blue screen (ide).
You didn't have to use any extra includes or statements for input, output.
With time that old PC went, taking the software with it.
(yes I do have newer versions like builder 5,6)
If anyone knows the version please let me know Thanks ahead of Time.
Borland C++ 3.1, too.
Visual C++ 6.0 and older.
iostream.h is the deprecated version.
use #include < iostream >
Namespaces help avoiding name collisions. The current standard has #include <iostream> substituting the previous #include <iostream.h>. You should get used to the std:: prefix to identify the namespace where the standard libraries live, or you can apply using directives to avoid having to write std:: all around:
#include <iostream>
using namespace std;
int main() {
cout << "No std:: required here" << endl;
}
The using directive tells the compiler to bring all identifiers from the namespace here, avoiding the need for qualification. Note that in the presence of ambiguities you will still need to fully qualify.
#include <iostream>
int cout;
int main() {
using namespace std;
::cout = 5;
std::cout << ::cout << endl;
}
iostream.h was a part of the standard library as documented by C++ Annotated Reference Manual (which was a de facto standard document prior to ISO standardization of the language).

C++ namespace and include

Why do we need both using namespace and include directives in C++ programs?
For example,
#include <iostream>
using namespace std;
int main() {
cout << "Hello world";
}
Why is it not enough to just have #include <iostream> or just have using namespace std and get rid of the other?
(I am thinking of an analogy with Java, where import java.net.* will import everything from java.net, you don't need to do anything else.)
using directives and include preprocessor directives are two different things. The include roughly corresponds to the CLASSPATH environment variable of Java, or the -cp option of the java virtual machine.
What it does is making the types known to the compiler. Just including <string> for example will make you able to refer to std::string :
#include <string>
#include <iostream>
int main() {
std::cout << std::string("hello, i'm a string");
}
Now, using directives are like import in Java. They make names visible in the scope they appear in, so you don't have to fully qualify them anymore. Like in Java, names used must be known before they can be made visible:
#include <string> // CLASSPATH, or -cp
#include <iostream>
// without import in java you would have to type java.lang.String .
// note it happens that java has a special rule to import java.lang.*
// automatically. but that doesn't happen for other packages
// (java.net for example). But for simplicity, i'm just using java.lang here.
using std::string; // import java.lang.String;
using namespace std; // import java.lang.*;
int main() {
cout << string("hello, i'm a string");
}
It's bad practice to use a using directive in header files, because that means every other source file that happens to include it will see those names using unqualified name lookup. Unlike in Java, where you only make names visible to the package the import line appears in, In C++ it can affect the whole program, if they include that file directly or indirectly.
Be careful when doing it at global scope even in implementation files. Better to use them as local as possible. For namespace std, i never use that. I, and many other people, just always write std:: in front of names. But if you happen to do it, do it like this:
#include <string>
#include <iostream>
int main() {
using namespace std;
cout << string("hello, i'm a string");
}
For what namespaces are and why you need them, please read the proposal Bjarne Stroustrup gave 1993 for adding them to the upcoming C++ Standard. It's well written:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0262.pdf
In C++ the concepts are separate. This is by design and useful.
You can include things that without namespaces would be ambiguous.
With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the using directive or if you did you would have to specify the namespace of the other stuff in the namespace you wanted.
Note also that you don't NEED the using - you can just used std::cout or whatever you need to access. You preface the items with the namespace.
In C++ #include and using have different functions.
#include puts the text of the included file into your source file (actually translation unit), namespaces on the other hand are just a mechanism for having unique names so that different people can create a "foo" object.
This comes from C++ not having the concept of a module.
Keep in mind that namespaces in C++ are open, that means that different files can define different parts of the same namespace (sort of like .NET's partial classes).
//a.h
namespace eg {
void foo();
}
//b.h
namespace eg {
void bar();
}
The include is defining the existence of the functions.
The using is making it easier to use them.
cout as defined in iostream is actually named "std::cout".
You could avoid using the namespace by writing.
std::cout << "Hello World";
These keywords are used for different purposes.
The using keyword makes a name from a namespace available for use in the current declarative region. Its mostly for convenience so that you do not have to use the fully qualified name all the time. This page explains it in some detail.
The #include statement is a pre processor directive and it tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. That is, you can think of this statement as copying the included file into the current one. The compiler then compiles the entire file as if you wrote all the code in one big file.
As pointed out, C++ and Java are different languages, and do somewhat different things. Further, C++ is more of a 'jest grew' language, and Java more of a designed language.
While using namespace std; isn't necessarily a bad idea, using it for all namespaces will eliminate the whole benefit. Namespaces exist so that you can write modules without regard to name clashes with other modules, and using namespace this; using namespace that; can create ambiguities.
I think the other answers are missing the point slightly. In all of C++, Java and C#, the using/import thing is entirely optional. So that's not different.
And then you have to do something else to make code be visible anyway, in all three platforms.
In C++, you minimally have to include it into the current translation unit (good enough for many implementations of vector, string, etc.), often you have to add something to your linker as well, although some libraries do that automatically based on the include (e.g. boost when building on Windows).
And in C# you have to add a reference to the other assembly. That takes care of the equivalent of includes and link settings.
And in Java you have to ensure the code is on the classpath, e.g. adding the relevant jar to it.
So there are very closely analogous things required on all three platforms, and the separation between using/import (a convenience) and actual linkage resolution (a requirement) is the same in all three.
You need to understand namespaces if you want to truly understand this.
With include you are just including the header file.
With using namespace you are declaring you are using a given namespace that contains stuff such as cout. so if you do this:
using namespace std;
to you use cout you can just do
cout << "Namespaces are good Fun";
instead of:
std::cout << "Namespaces are Awesome";
Note that if you do not #include <iostream> you won't be able to use neither std::cout nor cout in your declarations and so forth because you're not including the header.
One liner (not that this is something new :)):
using std allows you to omit std:: prefix, but you cannot use cout at all without iostream.
Even Stroustrup refers to the #include mechanism as somewhat hackish. However it does make separate compilation much easier (ship compiled libraries and headers instead of all source code).
The question really is "why did C++ -- after it already had the #include mechanism -- add namespaces?"
The best example I know of about why #include isn't enough comes from Sun. Apparently Sun developers had some trouble with one of their products because they had written a mktemp() function that happened to have the same signature as a mktemp() function that was included through from a file that was itself included through a header the project actually wanted.
Of course the two functions were not compatible, and one could not be used as a substitute for the other. On the other hand, the compiler and linker did not realize this when building the binary, and sometimes mktemp() would call one function, and sometimes it would call another, based on the order different files were compiled or linked.
The problem stems from the fact that C++ was originally compatible with -- and essentially piggy-backed on top of -- C. And C has only a global namespace. C++ solved this problem -- in code that is not compatible with C -- through namespaces.
Both C# and Java (1) have a namespace mechanism (namespace in C#, package in Java), (2) are usually developed through IDEs that handle referring to binaries for the developer, and (3) don't allow freestanding functions (a class scope is something of a namespace, and reduces the risk of polluting the global namespace) so they have a different solution to this problem. However, it is still possible to have some ambiguity regarding which method you're calling (say, a name clash between two interfaces that a class inherits), and in that case all three languages require the programmer to clearly specify which method they're actually looking for, usually by prepending the parent class/interface name.
In C++, the include directive will copy and paste the header file into your source code in the preprocessing step. It should be noted that a header file generally contains functions and classes declared within a namespace. For example, the <vector> header might look similar to something like this:
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
...
}
Supposing you need to define a vector in your main function, you do #include <vector> and you have the piece of code above in your code now:
namespace std {
template <class T, class Allocator = allocator<T> > class vector;
...
}
int main(){
/*you want to use vector here*/
}
Notice that in your code the vector class is still located in the std namespace. However, your main function is in the default global namespace, so simply including the header will not make the vector class visible in global namespace. You have to either use using or do prefixing like std::vector.