Difference between namespace , library and namespace

Hi Everybody,

I have started studying c++ and I came to know about header files , libraries and namespace. But I am confused regarding their differences . Header file contains the interface declaration , library contains their actual definition and what I understood till so does namespace so what are the difference ? why do we have so many terms? Kindly help me to understand
In short:

Header files are just more files that you can 'include' into your source code files. They normally (but don't have to) have interface declarations, so that each file knows that the so-and-so code exists somewhere else in your program, and you don't get compilation errors (unless, of course, the code doesn't exist). They are called header files because they are normally included at the 'head' (front, top) of your source code files.

A library is source code, rather than Header Files which are just definitions. However, a library is a combination of header files and source files, and some libraries (for example, Boost) can be pretty much header only.

A namespace is an actual C++ construct that separates the names of functions, classes and variables from each other, to prevent naming conflicts. For example:
1
2
3
4
5
6
7
namespace a {
    void func() { std::cout << "Hello World!"; }
}

namespace b {
    void func() { std::cout << "Goodbye Everybode!"; }
}

In the above code, if the two func()s weren't in namespaces, you would end up with errors (because you have given it two different definitions). However, with namespaces, you can specify that you want, for example, the func() in a by calling a::func(). An example that you should know of is the std namespace, such as in std::cout.
@NT3 and amirtok :

Does it mean namespace is a region which contains the header files(declarations ) and the libraries (source code )?
No.
Header files contain namespaces - not the other way round. Source files would have their code in namespaces too. Also, just to reiterate, a header file can have source code too, especially if you are using templates. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// header.h
#ifndef __HEADER_H_INCLUDED__
#define __HEADER_H_INCLUDED__

namespace a {
    template <typename T>
    T func(T a, T b) {
        return a + b;
    }
}

namespace b {
    template <typename T>
    T func(T a, T b) {
        return a < b ? a : b;
    }
}

#endif // __HEADER_H_INCLUDED__ 
Last edited on
Sorry to ask, this may sound stupid , but I am not getting how are namespace and libraries are related?
They aren't, not really (unless there is another meaning to namespace that I don't know of). A library, will, however, often have its code within a namespace, for example the GLM (header only) library contains all of its inteface in the glm namespace, and all of its implementation in the glm::detail namespace.
Topic archived. No new replies allowed.