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. 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’s 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

95 comments to 4.3b — Namespaces

  • Zafer

    What if we want to use Foo namespace first and then Goo namespace? Is it possible to discontinue using a namespace and start using another?

    • You can always reference a namespace directly using the scope resolution operator (::).

      However, if you want to use the using statement, I think the only way to do this would be to put the using statement inside it’s own block, along with the relevant code.

      Something like this:

      • chkwa

        this is useful, i suggest to add this example to above lesson.

        great tutorial!

      • I agree; it should be in the above examples as it’s not explained earlier. Other than this, I really enjoy your tutorials!

        Thank you Alex!

      • Hi Alex,

        You haven’t mentioned the possibility of creating an *alias* for a namespace;

        Did you omit this on purpose, and if so, why?

        BTW, thanks for a great website; it is superb.

        Regards,
        Kenneth aka ZNorQ.

  • Chad

    What about ‘namespace pollution’? You should never ‘use’ a namespace in a header file.

  • Pablo

    Why can’t I define a function outside a namespace once it has been declare in? For example the code:

    will issue the next error: Ambiguity between ‘mio::suma(int,int)’ and ‘suma(int,int)’ in function main().

    • Alex

      The problem isn’t that you’ve declared suma() outside of namespace mio. The problem is that you’ve declared “using namespace mio” in the global namespace. So when main() calls suma(), the compiler doesn’t know whether you mean ::suma() or mio::suma().

  • bashir

    question

    is “int main(void)” and “int main()” the same thing?

  • saini

    my question

  • well.. this didn’t seem like the hardest section (pointers was a hard concept for someone new to cpp), yet for some reason I cant get this to work!

    I’m also confused that you mention the header files, but then the functions that you use in the header files don’t look like simple prototypes, since they have a return statements, they look like full functions ..hmm

    The simplified example is below:

    header.h:
    #ifndef …etc

    externalFn.cpp:

    so in my main.cpp, I should just be able to use:
    main.cpp :

    but the only error I get is: undefined reference to ‘exf::bx()’
    I dont understand why, should we actually be defining the full functions (not just the proto) in the header files now?

    (The rest of this tutorial has been great by the way… Thank you so much for sharing your wealth of knowledge and teaching skills 😉 )

    • I’m not certain why, but removing the inline option (learnt in the previous lesson) solved my problem.

      • Pooja

        Hi mike22,

        I tried the same example with bit change as below:

        I am not sure how it solved the problem "undefined reference to `example::doSomething()".
        Alex/Mike22 can someone explain me how that change solved the issue?

        And also @Alex: Thanks for such a nice tutorial. It is helping me a lot

        • Alex

          In namespace.h, you’ve declared doSomething() to be inside namespace example.

          So in namepspace.cpp, when you define doSomething(), it should also be inside namespace example.

          If you don’t, then your declaration won’t match your definition, and the compiler will complain about something.

  • marjoonjan

    I’m confused! Consider “cin”, for example. It is in the namespace std. Is there any other namespaces with object “cin”? Otherwise, why we need to declare the namespace std::cin.
    In other words, would you please give me an example for two standard objects with the same name in different namespaces? (I mean an object that is not defined by user)

    • He used the ‘std::cin’ as an example to show you how it works.
      also, while I’m not aware of such colliding cases, it might be possible that custom namespaces have colliding names, and this is when it might come useful.

  • stpmazic

    Fantastic tutorial, I’m really enjoying it - thank you very much for sharing your knowledge, Alex. At this point of tutorial, I have a question:

    I followed the examples in this section, and found out everything works fine when using scope resolution operator:

    double dSin = 0.0;
    double dCos = 0.0;

    foo::GetSinCos(30.0, dSin, dCos);

    cout << "The sin is " << dSin << endl;
    cout << "The cos is " << dCos << endl;

    But when I try the "using namespace" keyword method, I get "ambiguous call to overloaded function" error:

    double dSin = 0.0;
    double dCos = 0.0;

    using namespace foo;
    GetSinCos(30.0, dSin, dCos);

    cout << "The sin is " << dSin << endl;
    cout << "The cos is " << dCos << endl;

    Does anyone have an idea why is this happening? Thanks 🙂

  • TAJ

    This tutorial is really very helpful.Thanks Alex.
    one comment on the header files included in the main.cpp
    User defined header files should be in double quotes(ex: #include “a.h”) otherwise compiler will throw an error.

  • Danny

    Hey, Alex. Thank you so much for this website -- you’re helping a lot of people, including myself. I have one recommendation, if you’re ever thinking about ways to make it even better. I think it would be tremendously helpful to have more bugged code examples for people to spot errors in. It would definitely help prepare us for coding out in the wild.

  • dngstr

    In the example, shouldn’t #include <foo.h> and #include <goo.h> be in quotation marks?  I thought the double quotes means that we’re supplying it.

  • Todd

    Typos.

    "as it increase (increases) the chance of identifiers from multiple namespaces (and the global scope) conflicting"

    I would also note that it’s odd to put "conflicting" so late in this clause. I would say something like, "as it increases the chance of conflicting identifiers from multiple namespaces (and the global scope)"

  • cpplx

    is there an actually defined namespace global?

    can we do that:
        //like std::cout. no "using"
        std::cout << Foo::doSomething(4, 3) << endl;
    instead of:
        …
        using Foo::doSomething;
        cout << doSomething(4, 3) << endl;
    ?

    if above is possible where does the namespace get terminated after it(scope, duration)?

    • Alex

      The global namespace is essentially what we call everything that isn’t in a different namespace.

      Yes, you can explicitly call Foo::doSomething().

  • techsavvy....aye

    Is the following program correct

    foo.cpp

    foo.h

    • Alex

      Mostly. foo.cpp needs to #include foo.h. foo.h should also have header guards.

      However, generally it’s considered bad form to define function in a .h file. It would be better to put the code in foo.h in foo.cpp, and then use a forward declaration (in Foo.h) to access Foo::doSomething().

      main.cpp

      foo.h:

      foo.cpp

  • Cloverfield

    Thanks once again for the great tutorials and the disambiguation of Namespaces. I have a little question though.
    foo.h

    goo.h

    Main

    If a namespace is declared/defined in multiple files, Can i build this whole Namespace without having to include every [header] that has something new for this namespace?(a new Function, or a variable).I mean, have you ever used multiple files to declare/define a namespace? Is this practical? Wouldn’t be better to be all the stuff in a coherent namespace alone?(like std)?. Can i compile somehow the whole namespace alone, and then use it in main as something coherent,consistent?
    Keep tutoring 😉

    • Alex

      > If a namespace is declared/defined in multiple files, Can i build this whole Namespace without having to include every [header] that has something new for this namespace?(a new Function, or a variable).

      You could, if you really wanted to. In your example above, you could create a MathFunctions.h that #included foo.h and goo.h (and any other header that used namespace MathFunctions). Then instead of #including foo.h or goo.h, you could include MathFunctions.h and get everything in the MathFunction namespace.

      But this isn’t how namespaces are meant to be used. If you look at the standard library, there’s no std.h that includes everything in the std namespace. Instead, things are organized by function -- if you need input/output, you #include . If you need to work with text, you include . This way, you only #include what you actually need, and you don’t get things you don’t need.

      If you always want Add(), Subtract(), Multiply() , and Divide() to be included together, then either put them in same header (recommended), or create a MathFunctions.h header that includes foo.h and goo.h.

  • Cloverfield

    Thanks a lot!!!

  • Hello,
    Look at the following snipped :

    Is foo variable in the global namespace ?
    I mean : When we declare a var in a function, Is that Variable in the global namespace ?

    • Alex

      Good question. Local variables aren’t considered part of the global namespace. They’re local to the block they are declared in.

  • Hi Alex,
    Can we say ? : << a namespace is a label for a local area and it can called when we need it’s contents ? >>
    is this a good definition for namespace ?!

  • Alex, can’t we declare a namespace inside a function?

    This gives a compiler error: "fire.cpp|5|error: ‘namespace’ definition is not allowed here|"
    Why?
    (could be a silly syntatical mistake, if found, please point it out)

    • Alex

      Nope. Namespaces can’t be inside a function. They have to be at global scope, or inside another namespace.

      It wouldn’t really make sense to have namespaces inside functions. The odds of having a naming collision within a single function is essentially zero, and if it did happen, it would be really easy to fix.

  • Salman Sajid

    How can i use namespace within multiple location??
    Thnx in advance!

  • Jim

    Alex,
    I disagree with the wording you wrote under "What is a namespace?" its shown below.

    "A namespace defines an area of code in which all identifiers are guaranteed to be unique. By default, all variables and functions are defined in the global namespace."

    If a namespace is guaranteed to be unique then all variables and functions can not be defined or live in the global namespace.

    Yet, we could say a function lives in it own unique namespace which includes an identifier and could include some variables. On the other hand all of the commands used in C++ are defined in a unique namespace the STL.

    • Alex

      I’ve updated the wording slightly to say, “By default, global variables and normal functions are defined in the global namespace”. Does this meet your concern?

  • Jim

    Alex,
    Looks good to me. Thanks

  • Jim

    Alex,

    In a lot of your lessons you’ve list various rules to follow. I was thinking it might be a good idea to compile them all into one list.  Then we could print it out or put it in a notebook to refer to.

    If this is not to much trouble would you please do that. Thanks

  • Soul

    Hi, I need some help please.

    I tried making this namespace and main, but every time the namespace wants to execute first and runs every myName and myAge variable within rather than wait for a call from main. Why does this occur?

    My intention was to make a namespace that held variables for names and for the only way to alter those names being functions within the namespace. I tried sticking the namespace in a separate file but that didn’t help.

    Is the only way to do what I’m thinking of would be to make a separate file with the student names being static and for ‘access’ functions to be the only way to display them when called?

    I’m trying (as practice) to make a program with what I’ve learned that’ll store names and ages and then display them as a list to be chosen from (a-c). The choices a-c would be char that the user inputs.

    • Alex

      Global variables (including those in a namespace) are initialized before main() starts. You are calling Ager() during this initialization, so Ager() is getting run before main().

      Namespaces were designed to help prevent naming collisions, not for access control (making it so you can/can’t access variables from outside the namespace). If you want access control, you can do one of two things:
      1) Put the variables in a separate file (they don’t have to be namespaced) and provide functions to get/set the values of those variables (and a header file with forward declarations for those functions). Your main program will be able to #include the header and access the functions, but won’t be able to see the variables themselves directly.
      2) Use a class. Classes have access-control mechanisms.

      For now, #1 is probably your better option since we haven’t covered classes yet.

  • Muhammad Umar Tariq

    in the chapters in the beginning it is written that you can only declare function prototypes inside a header file

    so while making namespaces like in this lesson can we fully define functions inside the namespaces ?

    also should we code entire classes with function definitions inside namespaces inside a header file ? or just the class declaration and prototypes of it’s functions ?

    • Alex

      > in the chapters in the beginning it is written that you can only declare function prototypes inside a header file

      Where did it say that? You can define functions anywhere in the global namespace (including inside your own namespaces). This includes both in code files and headers. You can also forward declare functions using the function prototype anywhere in the global namespace. Typically you’ll define the functions in a .cpp file, and put the forward declaration in a header, so you can #include the header to use the function.

      When it comes to classes, for trivial classes you might define the whole thing in a header file (or in a code file if it’s only used in a single file). For more complicated classes, you’ll probably declare the class in the header file and the class functions in a code file. Whether the class is in a namespace or not is up to you. Personally, I typically don’t put my classes inside namespaces, but I would if I was going to distribute them as a library or something.

  • Lokesh

    "You can still get naming collisions with using declarations:"
    should be
    "You can still get naming collisions with using directives:"

  • Shiva

    Hey Alex,

    Intuitive lesson, once again. I am not asking why a lot of text in this webpage is strangely bold, but I do have one tiny question - can we define namespaced functions using the Scope Resolution Operator? For example, in your reply to techsavvy….aye’s comment above, you defined doSomething in foo.cpp. Instead of that code, can we define doSomthing() as:

    Is this possible? Or do we have to follow the same structure as in ur comment? I know it’s silly, just wanted to know. 🙂

  • Jim

    Alex,
    This may seem like a dumb question but why did you not include the .h ( header) on foo.h and goo.h, or when you used them with the scope res. operator foo:: or namespace foo?
    It will be hard to remember to leave the out.  What happens if their includes?

    So to declare a namespace all you need to do is put namespace (name).  Are there any conflicts with using namespaces std in the same functions with other namespaces?

    Does namespace have the same rules as variables as far as being in a block is local and all others default to global?
    Thanks for all your hard work.

    • Alex

      We use #include statements to include things from .h files. When we #include foo.h, that brings in both the foo namespace and function doSomething() into the main.cpp file.

      Then, to reference the namespace itself, we just use the name of the namespace as the prefix (foo::doSomething()). It’s just coincidental that the name of the namespace and the header file are similar in this example.

      You can still get conflicts between the std namespace and your namespace if you use stuff from the std namespace inside your namespace and the names conflict. So you still have to be careful.

      Namespaces must be in the global scope (or inside another namespace). So you can’t define them inside a local block at all.

  • 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.

  • 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.

  • 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 ?

  • 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. 🙂

  • 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). 🙂

  • 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.

  • 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.

  • 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).

  • 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?

  • 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.

  • 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.

Leave a Comment

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