Search

4.3b — Namespaces

In lesson 1.8a -- Naming conflicts and the std namespace, we introduced the concept of naming conflicts and namespaces. This lesson builds upon those topics.

A naming conflict occurs when two identifiers are introduced into the same scope, and the compiler can’t disambiguate which one to use. When this happens, compiler or linker will produce an error because it does not have enough information to resolve the ambiguity. As programs get larger and larger, the number of identifiers increases linearly, which in turn causes the probability of naming collisions to increase exponentially.

Let’s take a look at an example of a naming collision. In the following example, foo.h and goo.h are the header files that contain functions that do different things but have the same name and parameters.

foo.h:

goo.h:

main.cpp:

If foo.h and goo.h are compiled separately, they will each compile without incident. However, by including them in the same program, we have now introduced two different functions with the same name and parameters into the same scope (the global scope), which causes a naming collision. As a result, the compiler will issue an error:

c:\VCProjects\goo.h(4) : error C2084: function 'int __cdecl doSomething(int,int)' already has a body

In order to help address this type of problem, the concept of namespaces was introduced.

What is a namespace?

A namespace defines an area of code in which all identifiers are guaranteed to be unique. By default, global variables and normal functions are defined in the global namespace. For example, take a look at the following snippet:

Both global variable g_x and function foo() are defined in the global namespace.

In the example program above that had the naming collision, when main() #included both foo.h and goo.h, both versions of doSomething() were included into the global namespace, which is why the naming collision resulted.

In order to help avoid issues where two independent pieces of code have naming collisions with each other when used together, C++ allows us to declare our own namespaces via the namespace keyword. Anything declared inside a user-defined namespace belongs to that namespace, not the global namespace.

Here is an example of the headers in the first example rewritten using namespaces:

foo.h:

goo.h:

Now the doSomething() inside of foo.h is inside the Foo namespace, and the doSomething() inside of goo.h is inside the Goo namespace. Let’s see what happens when we recompile main.cpp:

The answer is that we now get another error!

C:\VCProjects\Test.cpp(15) : error C2065: 'doSomething' : undeclared identifier

What happened is that when we tried to call the doSomething() function, the compiler looked in the global namespace to see if it could find a definition of doSomething(). However, because neither of our doSomething() functions live in the global namespace any more, it failed to find a definition at all!

There are two different ways to tell the compiler which version of doSomething to use, via the scope resolution operator, or via using statements (which we’ll discuss in the next lesson).

Accessing a namespace with the scope resolution operator (::)

The first way to tell the compiler to look in a particular namespace for an identifier is to use the scope resolution operator (::). This operator allows you to prefix an identifier name with the namespace you wish to use.

Here is an example of using the scope resolution operator to tell the compiler that we explicitly want to use the version of doSomething that lives in the Foo namespace:

This produces the result:

7

If we wanted to use the version of doSomething() that lives in Goo instead:

This produces the result:

1

The scope resolution operator is very nice because it allows us to specifically pick which namespace we want to look in. It even allows us to do the following:

This produces the result:

7
1

It is also possible to use the scope resolution operator without any namespace (eg. ::doSomething). In that case, it refers to the global namespace.

Multiple namespace blocks with the same name allowed

It’s legal to declare namespace blocks in multiple locations (either across multiple files, or multiple places within in the same file). All declarations within the namespace block are considered part of the namespace.

add.h:

subtract.h:

main.cpp:

This works exactly as you would expect.

The standard library makes extensive use of this feature, as all of the different header files included with the standard library have their functionality inside namespace std.

Nested namespaces and namespace aliases

Namespaces can be nested inside other namespaces. For example:

Note that because namespace Goo is inside of namespace Foo, we access g_x as Foo::Goo::g_x.

Because typing the fully qualified name of a variable or function inside a nested namespace can be painful, C++ allows you to create namespace aliases.

It’s worth noting that namespaces in C++ were not designed as a way to implement an information hierarchy -- they were designed primarily as a mechanism for preventing naming collisions. As evidence of this, note that the entirety of the standard template library lives under the singular namespace std::. Some newer languages (such as C#) differ from C++ in this regard.

In general, you should avoid nesting namespaces if possible, and there are few good reasons to nest them more than 2 levels deep. However, in later lessons, we will see other related cases where the scope resolution operator needs to be used more than once.

4.3c -- Using statements
Index
4.3a -- Scope, duration, and linkage summary

134 comments to 4.3b — Namespaces

  • noobofcpp

    Hi Alex I love your tutorial easy to understand and your tutorial is the best I found.I just wonder how it takes to master C++.
    Why don’t you write your own book.You know some people prefer printed book.

  • Hema

    Shouldn’t there be a semi-colon after namespace foo and namespace goo ?

  • Hema

    Which one is better-  #include "XYZ.h"  or  #include <XYZ.cpp>

  • fsguzi

    Based on the previous sections, variables declared in a block have local scope. So if we declare a variable someVar in a namespace block, say someNamespace, someVar is only accessed from with in the block. But when we use the identifier someNamespace::someVar to refer to this variable from outside of someNamespace block, we are effectively accessing someVar, contradicting the concept of ‘local variable’.

    Is there a better way to interpret/explain this? So far I try to see the entire namespace block as a special function which ‘sells’ data local to itself, but how does it differ from other types of blocks(e.g. function definition) on the backend/compiler(tbh I don’t really know what it is) level?

    Great site btw. Plenty of examples and good tips for programming in general.

    • Alex

      I think I see where your confusion is coming from.

      Both namespaces and function braces provide scoping for the identifiers declared inside, from the point of declaration to the closing brace (for namespaces, also to other identically named namespaces that follow).

      With block scope, identifiers declared inside the block are always local to that block. You’re not allowed to access the contents of the block from outside the block (there’s no way to even reference the block, and the variables don’t exist when the block isn’t being executed). In this sense, the contents of a block are private.

      On the other hand, with namespaces, identifiers declared inside the namespace are always global. This makes sense: global identifiers are defined in the global namespace. User-defined namespaces are defined inside the global namespace, making them globally accessible as well. The namespace doesn’t restrict access to the contents of the namespace -- rather, it just changes how those identifiers need to be qualified to be referenced.

      Make sense?

  • Zero Cool

    In the last paragraph in the part of "and there’s few good reasons to nest them more than 2 levels deep." you should use ‘re instead of ‘s right???

    Maybe I am wrong with this typo but well my first language is Spanish after all

    Thanks Alex for this amazing tutorial once more.

  • Marius

    Hello, Alex!

    I am wondering why you show here and other places that you put function definitions in header files.
    Is it for sake of simplicity? Or am I just mistaking and it is actually legal to do so?

    Thank you for any response.

    • Alex

      When I do this, it’s generally for the sake of simplicity. Although it is legal to do so, it’s likely to lead to problems in non-trivial cases.

  • justAnotherConfusedStudent

    Hi Alex,

    I have a question about a certain sentence of yours. You mentioned, back in the beginning, that "As programs get larger and larger, the number of identifiers increases linearly, which in turn causes the probability of naming collisions to increase exponentially."

    I’ve taken some discrete math, and I’m wondering how exactly this calculation is performed, if you know?

    • Alex

      The way I figure, any name can collide with any other name. So if you have N non-colliding names, and you add one more, your odds of collision just increased by N. So I think the formula for number of possible collisions with N identifiers would be N(N-1)/2, which is exponential.

  • Hardik

    tut.cpp

    tut.h

    constants.cpp

    tut.h and constants.cpp are in the same project (tutorial.cbp) !
    When i call add() from namespace math from main() in tut.cpp, it gives a linker error…Why?

    • Alex

      Edit: I misdiagnosed the problem, so removing my original comment so as not to cause confusion. The author’s solution to the issue is in a sub-comment below.

      • Hardik

        Btw U didnt see properly, i have given a fwd. declaration of function add() in tut.h. But, thanks btw. I fixed it !

      • erad

        @ Alex,

        I respectfully disagree with your explanation. His header file rightfully had a function prototype/forward declaration for add(int,int) and its corresponding definition is in the .cpp file.

        My thought is that the reason for the linker error was because the names of the .h and .cpp files do not match! i.e. he used tut.h and constants.cpp. Is it not a requirement for the names to match (i.e. the same) to prevent a linker error??

        Great job on the site! Keep it up.

        • Alex

          You’re partly correct: I misdiagnosed the problem. The author indicated that he forgot to include constants.cpp in his project, so it didn’t get compiled.

          However, it’s also worth noting that C++ doesn’t care are all what the name of the files are.

          • erad

            @ Alex,

            You wrote: "However, it’s also worth noting that C++ doesn’t care are all what the name of the files are."

            Let’s say the "namespace math" requirement were dropped (i.e. assume that the forward declaration and the function definition for "int add" do not exist in the math namespace), would the quote above from your comment still hold? In other words, there would be no linker error as long as all the files are included in the same project?

            If the answer to the above is YES, is it correct to say that what prevents a linker error is the mere presence of a corresponding function definition for a particular forward declaration, irrespective of where that function definition is?

            And if the answer to the above is also YES, so whether there is a correlation in the .h file name and the .cpp file name is a programmer’s choice, just for convenience?

            • Alex

              > In other words, there would be no linker error as long as all the files are included in the same project?

              Yes.

              > is it correct to say that what prevents a linker error is the mere presence of a corresponding function definition for a particular forward declaration, irrespective of where that function definition is?

              Yes. Forward declarations tell the compiler that the function definition exists somewhere, but not where. The linker connects the function call to wherever the actual function definition is (possibly in a different file altogether).

              > whether there is a correlation in the .h file name and the .cpp file name is a programmer’s choice, just for convenience?

              Yes, the correlated names is just a best practice to help the programmer keep track of which set of declarations go with which set of definitions.

    • Alex

      main.cpp #includes tut.h, which has a definition for function add(), so that definition gets copied into main.cpp and compiled. constant.cpp has it’s own definition for add(). So now you have two definitions for the same function, and because functions have external linkage, the collide (have a naming collision) when you try to call them.

  • James Ray

    Hi Alex,

    This tutorial also uses cout rather than std::cout a few times.

  • Nguyen

    Hi Alex,

    I have a question about Global namespace in the first example.  Please let me know if each file (foo.h, goo.h, main.cpp) had its own Global namespace?

    You wrote "when main() #included both foo.h and goo.h, both versions of doSomething() were included into the global namespace, which is why the naming collision resulted." I am assuming that both versions of doSomething() were included into the global namespace of main.cpp?  

    Thanks, Have a great day.

    • Alex

      There is only one global namespace. However, this in and of itself isn’t sufficient for a collision to occur. For a collision to occur, two names must be introduced into the same scope AND the compiler must not be able to disambiguate them. So long as the names are kept in separate scopes (e.g. in different files with internal linkage), or if the compiler can disambiguate them via some other means (e.g. function overloading), then they won’t collide even if they share a name.

  • Nguyen

    Hi Alex,

    I have a question about the example in "Multiple namespace blocks with the same name allowed".  What would happen if I try to change all the function names (add in add.h, subtract in subtract.hh, and add/subtract in main.cpp) to the same name (for example: doSomething) ?.  

    Thanks, Have a great day.

  • JeffR

    No questions, I just wanted to complement you on the quality of this site. Great job. 🙂

  • Benji

    This course is awesome! Thank you whoever created this class! Much obliged. **tips hat**

  • Don jose

    Hi Alex,

    Thanks a lot for the replay. I got now,  the link you shared is more informative and I read some other topics as well. this is very nice experience for me.

    Whenever I get any doubt, I always remember your name. This site helped me a lot. I completed your tutorials up to templets and error handling. this is simply awesome

    Now  am trying to understand the way of using all this knowledge in real project by using some open source project like stockfish_chess engine

    Once again thanks a lot.

  • Don jose

    Hi Alex,

    Please find the code snippet

    surprising thing for me is here no name for the namespace, then how it useful?
    Can you please tell me what it means and use of this

    the code is something like this

    Thanks in advance

    • Alex

      I don’t understand the question.

      • Dohn jose

        Hi Alex,

        In the above snippet, a namespace region is created without any specified name to the namespace, Like

        How can we access the variable inside this namespace, need to use any namespace resolution(::) for this area

        Or it just like a plain area and can access without specifying any namespace resolution.
        if it is a plain area, then why it used like this (I saw this type of coding in stockFish open source project for chess engine)

        I hope you can understand my explanation,

        • Alex

          Oh, yes, I see. You’re asking about unnamed namespaces.

          According to the C++ spec, an unnamed namespace behaves as if it were replaced by:

          In essence, everything inside the unnamed namespace is placed into the global scope, but is only accessible in that particular translation unit/file.

          This is essentially a much-less-used but superior method to using the static keyword to make your variables and functions have internal linkage.

          See this FAQ answer for more information about this.

  • Ayush Sharma

    I visited the mobile version of this website.
    This site looks way more advanced and neat on a mobile phone.
    Why isn’t the desktop version of this site changed to that kind of interface?

  • Matt

    Should namespace functions be declared AND defined within the namespace, or is it more proper to define the function outside of the namespace block using the scope resolution operator? Or, should they be defined within a seperate block with the same namespace name?

    Also, with my limited comprehension so far, it seems to make sense that namespaces should only be declared within header files, and every header file should be namespaced. That is to say, everything in the header file(except for the header gaurd), should be within a namespace(probably named after the header file). But I’m sure this is not the case, because I feel like I’m nowhere near seeing the bigger picture yet.

    • Alex

      When dealing with namespaces, you’ll most commonly see functions declared inside a namespace block in the header, and defined inside a namespace block in the corresponding .cpp file. Trivial functions (e.g. one liners) may be defined in the header (inside the namespace).

      Best practice is to put all of your code into namespaces. But realistically, many developers I’ve met and much of the code I’ve seen don’t follow this practice (with the exception of library code, which generally does).

  • Raquib

    Hi Alex,

    1> I am confused a bit with "using". Is it a "keyword" or a "directive"? I expected it to be a keyword. Becoz I remember reading in the "preprocessor" lesson, you mentioned, Directive are specific instructions that start with # symbol and end with new line (no semi-colon). The preprocessor will scan through the code and look for these directives. "using" doesn’t have a # sign, so why is it directive if it is? or am I missing something here???.

    2> And, if I understanding everything properly from previous lessons, it isn’t a good practice to define your function in a header file, which should typically contain forward declarations, where as definitions in a cpp source file. And to prevent these function forward declarations or variable forward declarations inside a header file from having naming collisions (as all of these by default end up in the global namespace) we limit their scope using keyword "namespace" and defining specific areas for them. Say "namespace functions" and "namespace variables" .
    If that’s the case, in this tutorial when you explained "namespace", in a headerfile you have defined functions under a namespace foo. Was it done intentionally for simplicity?? is the prior concept of headerfile holding just forward declaration being a good practice and recommended, still true??
    or am I making a mistake by considering it as a "carved in stone" rule of good programming.

    • Alex

      1) Using is a keyword. In the preprocessor lesson, we talked about preprocessor directives, which start with #. However, there are other kinds of (non-preprocessor) directives as well, such as using directives.

      2) Simplicity. Generally you should try to keep function definitions out of your headers and instead use them to propagate forward declarations.

  • Dimek

    Alex,
    If main.cpp is in a different file and you include foo.h in main.cpp, would you need to include foo.cpp also in main.cpp?

    • Alex

      There may not be a foo.cpp (header files don’t have to have a corresponding .cpp file). However, if there is a foo.cpp, you should not #include it from main.cpp (you should only #include headers, not code files). Instead, you should add foo.cpp to your project so your compiler compiles it as a separate file.

  • Hamd

    Thank you for the swift response Alex!

    Although, FAQ isn’t a bad idea and hopefully many will read it too. But the truth is, it is more interactive and learning this way (I mean asking questions here and reading through replies). 🙂

  • Hamd

    Regarding first example that included foo.h and goo.h, when does the header guards’ comes into play? The purpose of the header guard was to prevent the same thing from including twice?

    • Alex

      Header guards only prevent the same header from being included more than once into a given file. They do not prevent different headers from being included (once each). In the foo and goo case, header guards wouldn’t help since they are different headers.

      • Darren

        This question and answer about header guards pop up A LOT in these comments. You could have a FAQ page to which to bat these questions.

        • Alex

          Yeah, right? I think this is the most common misunderstanding in C++ for new programmers. A FAQ isn’t a bad idea -- but I suspect most readers won’t read it before just asking the question anyway. Such is human nature, it seems. 🙂

  • J3ANP3T3R

    Quesiton :

    "The using directive tells the compiler that if it can not find the definition for an identifier, it should look in a particular namespace to see if it exists there. "

    what if i wanted to use doSomething from Foo … then typed "using namespace Foo;" but the compiler DID find namespace Goo and it has doSomething as well and since the description above says "if it can not find the definition for an identifier" will it end up using Goo::doSomething instead of what i stated as using ?

    • Alex

      The compiler wouldn’t know to look in namespace goo unless you told it somehow (either via the goo:: prefix) or a using directive or declaration.

      I’m not sure if I’m answering your question, but consider the following program:

      • J3ANP3T3R

        well like …

        // someotherfile.cpp or someotherfile.h
        namespace foo
        {
            int doSomething()
            {
                return 5;
            }
        }

        // main.cpp
        int doSomething()
        {
            return 2;
        }

        int main()
        {
            using namespace foo; // tell compiler we want to use doSomething from namespace foo
            doSomething(); // compiler DOES find a function doSomething in main.cpp

            return 0;
        }

        so given that it will only look for an identifier in a particular namespace IF it cant find it here (in this case it did find it) is it going to use the one from foo or the one in main.cpp ?

  • Chris

    Sorry Alex, maybe because my English is so bad so I can’t understand with this sentence "This includes header files!" In the using keyword section, specifically at there "Rule: Don’t use the “using” keyword in the global scope. This includes header files!".

    Is it mean we shouldn’t includes header files in global scope? Or we shouldn’t use the using keyword in header files? Or what?

    Thank you.

    • Alex

      Don’t put using statements in header files (unless they’re inside a function that is defined in the header file). Otherwise when you #include the header file, the using statement will be copied into the global scope of every file that includes that header.

  • Oeleo

    Alex, i think that you forgot to end something to put a line in bold. I mean after this line :
    "Nested namespaces and namespace aliases"
    the rest of the lesson and all the comments are in bold.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter