Search

6.2 — User-defined namespaces

In lesson 2.9 -- Naming collisions and an introduction to namespaces, we introduced the concept of naming collisions and namespaces. As a reminder, a naming collision occurs when two identical 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 they do not have enough information to resolve the ambiguity. As programs become larger, the number of identifiers increases linearly, which in turn causes the probability of a naming collision occurring to increase exponentially.

Let’s revisit an example of a naming collision, and then show how we can resolve it using namespaces. In the following example, foo.cpp and goo.cpp are the source files that contain functions that do different things but have the same name and parameters.

foo.cpp:

goo.cpp:

main.cpp:

If this project contains only foo.cpp or goo.cpp (but not both), it will compile and run without incident. However, by compiling both into 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 linker will issue an error:

goo.cpp:3: multiple definition of `doSomething(int, int)'; foo.cpp:3: first defined here

Note that this error happens at the point of redefinition, so it doesn’t matter whether function doSomething is ever called.

One way to resolve this would be to rename one of the functions, so the names no longer collide. But this would also require changing the names of all the function calls, which can be a pain, and is subject to error. A better way to avoid collisions is to put your functions into your own namespaces. For this reason the standard library was moved into the std namespace.

Defining your own namespaces

C++ allows us to define our own namespaces via the namespace keyword. Namespaces that you create for your own declarations are called user-defined namespaces. Namespaces provided by C++ (such as the global namespace) or by libraries (such as namespace std) are not considered user-defined namespaces.

Namespace identifiers are typically non-capitalized.

Here is an example of the files in the prior example rewritten using namespaces:

foo.cpp:

goo.cpp:

Now doSomething() inside of foo.cpp is inside the foo namespace, and the doSomething() inside of goo.cpp is inside the goo namespace. Let’s see what happens when we recompile our program.

main.cpp:

The answer is that we now get another error!

ConsoleApplication1.obj : error LNK2019: unresolved external symbol "int __cdecl doSomething(int,int)" (?doSomething@@YAHHH@Z) referenced in function _main

In this case, the compiler was satisfied (by our forward declaration), but the linker could not find a definition for doSomething in the global namespace. This is because both of our versions of doSomething are no longer in the global namespace!

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 a later lesson in this chapter).

For the subsequent examples, we’ll collapse our examples down to a one-file solution for ease of reading.

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

The best way to tell the compiler to look in a particular namespace for an identifier is to use the scope resolution operator (::). The scope resolution operator tells the compiler that the identifier specified by the right-hand operand should be looked for in the scope of the left-hand operand.

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 expected 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 great because it allows us to explicitly pick which namespace we want to look in, so there’s no potential ambiguity. We can even do the following:

This produces the result:

7
1

Scope resolution with no prefix

The scope resolution operator can also be used without any preceding namespace (eg. ::doSomething). In such a case, the identifier (e.g. doSomething) is looked for in the global namespace.

So why would you actually want to do this? In most cases, you won’t. But we’ll see examples where this becomes useful in future lessons.

Multiple namespace blocks allowed

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

circle.h:

growth.h:

main.cpp:

This works exactly as you would expect:

3.14
2.7

The standard library makes extensive use of this feature, as each standard library header file contains its declarations inside a namespace std block contained within that header file. Otherwise the entire standard library would have to be defined in a single header file!

Note that this capability also means you could add your own functionality to the std namespace. Doing so causes undefined behavior most of the time, because the std namespace has a special rule, prohibiting extension from user code.

Warning

Do not add custom functionality to the std namespace.

When you separate your code into multiple files, you’ll have to use a namespace in the header and source file.

add.h

add.cpp

main.cpp

If the namespace is omitted in the source file, the linker won’t find a definition of basicMath::add, because the source file only defines add (global namespace). If the namespace is omitted in the header file, “main.cpp” won’t be able to use basicMath::add, because it only sees a declaration for add (global namespace).

Nested namespaces

Namespaces can be nested inside other namespaces. For example:

Note that because namespace goo is inside of namespace foo, we access add as foo::goo::add.

In C++17, nested namespaces can also be declared this way:

Namespace aliases

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, which allow us to temporarily shorten a long sequence of namespaces into something shorter:

One nice advantage of namespace aliases: If you ever want to move the functionality within foo::goo to a different place, you can just update the boo alias to reflect the new destination, rather than having to find/replace every instance of foo::goo.

It’s worth noting that namespaces in C++ were not originally 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 library lives under the singular namespace std:: (with some nested namespaces used for newer library features). Some newer languages (such as C#) differ from C++ in this regard.

In general, you should avoid deeply nested namespaces.

When you should use namespaces

In applications, namespaces can be used to separate application-specific code from code that might be reusable later (e.g. math functions). For example, physical and math functions could go into one namespace (e.g. math::). Language and localization functions in another (e.g. lang::).

When you write a library or code that you want to distribute to others, always place your code inside a namespace. The code your library is used in may not follow best practices -- in such a case, if your library’s declarations aren’t in a namespace, there’s an elevated chance for naming conflicts to occur. As an additional advantage, placing library code inside a namespace also allows the user to see the contents of your library by using their editor’s auto-complete and suggestion feature.


6.3 -- Local variables
Index
6.1 -- Compound statements (blocks)

266 comments to 6.2 — User-defined namespaces

  • Robbas

    Hello, I'd like a clarification. So from now on, if I need to propagate forward declarations, symbolic costants and global variables on multiple files, I have to do:

    1) Create a header file .h and a file .cpp
    2) Inside the header file, I create a namespace in which I will insert all my forward declarations, symbolic costants and global variables.
    3) Inside the file .cpp, I create the same namespace that I created in the file .h  and I will insert all my function definitions so compiler and linker don't complain.
    is it correct?

    P.S.
    To declare namespace blocks in multiple locations, it's something we must avoid if we can or not?

    Thank you in advance and thanks again for your fantastic work.

    • nascardriver

      hi!

      That's correct. Namespaces can be split into multiple parts, and you'll have to do so to separate your code into multiple files. There's nothing bad about this.

  • Louis Cloete

    Hi!

    The last sentence before "Defining your own namespaces" reads a bit clumsily. I'd suggest to amend it to

    "A better way to avoid collisions is to put your functions into your own namespaces. For this reason the standard library was moved into the std namespace."

  • salah

    Hi nascardriver,
    I did something like that and it worked:

    .h file:

    namespace salah
    {
      int return_three();
    }
    ____________________________

    .cpp file:
    #include header_file
    salah::return_three(){return 3;}

    and I could use the function without rewrite the namespace again in .cpp file, is it consider a correct way to define your namespace functions in this style ??

    • nascardriver

      If you have just 1 entity (function or variable) in the namespace, this can save you some typing. It's rare that you have just 1 entity in a namespace, so putting the definitions in a namespace block is easier.
      What you did can be confusing, because that syntax is used for class-member definitions (Covered later). I'd stick with a full namespace block.

  • Wolfma

    I think after the first code-block in the section about nested namespaces it should say: "Note that because namespace goo is inside of namespace foo, we access add() as foo::goo::add()." instead of: "Note that because namespace goo is inside of namespace foo, we access g_x as foo::goo::g_x.". I guess this comes from an old example that can be found in the comments.

    Thanks a lot for your great work!

  • Rauken

    I trying to find out why i can't get it to work, any suggestions?

    goo.cpp
    code
    namespace goo
    {
        int doSomething(int x, int y)
        {
            return x - y;
        }
    }
    /code

    foo.cpp
    code
    namespace foo
    {
        int doSomething(int x, int y)
        {
            return x + y;
        }
    }
    /code
    main.cpp
    code
    #include <iostream>
    #include "foo.cpp"
    #include "goo.cpp"

    int main()
    {
        std::cout << foo::doSomething(4, 3) << '\n'; // use the doSomething() that exists in namespace foo
        std::cout << goo::doSomething(4, 3) << '\n'; // use the doSomething() that exists in namespace goo
        return 0;
    }
    /code

  • kavin

    Hi i have a doubt.
    Under "Accessing a namespace with the scope resolution operator (::)" , instead of using  one-file solution for ease of reading , if we put "namespace foo" in a another .cpp file then , it shows the following error.
    error C2653: 'foo': is not a class or namespace name
    error C3861: 'doSomething': identifier not found

    But if i change it to (.h) file , then it compiles without error with required output.

    If we have to use a (.h) file instead like you have given in the next set of examples, then it contradicts the general advice given in previous chapter"4.13 const-constexpr-and-symbolic-constants" of not using functions in header files right ?

    • nascardriver

      .h files aren't compiled if you don't include them. You can make as many mistakes as you want, the compiler won't complain.

      You can move the definition of `foo::doSomething` into a .cpp file, but you'll need a forward declaration to access it from "main.cpp".

      I added an example of separating code into header and source while using namespaces in the "Multiple namespace blocks allowed" section.

      • kavin

        Thank you. Now i understand. Which one do you recommend to use ? Header with func definition or func definition in separate .cpp file with a header file?(considering our program is going to be a lengthy one with additional header statements too)

        • nascardriver

          Always put definitions in source files. Headers are for declarations.
          This lesson will be updated to remove the definitions in headers.

  • koe

    Hi, it might be helpful to point out how to put functions in namespaces. It looks like there was a recent comment explaining this. It said you should have a source file with the namespaced functions, and a header file with the namespaced forward declarations. Functions shouldn't go in the header files, even though using static kind of works.

    The method is somewhat implied by section S.4.2 on global symbolic constants.

  • Daniel

    Hey,

    What are some bad habits and good habits in context of namespaces e.g. should I use different namespace for whole project, every few classes that share common properties and every single file in project or should I use it more cautiously?

    I might google it, but I think it's a good idea to add this question here given this whole tutorial is being rewriten and this might be good thing to add into it.

    btw. Thx for this whole tutorial, its really great. I love that you learn all the good habits and pitfalls of the C++, so we can actually become fluent in this language :)

    • nascardriver

      Hey Daniel,

      I updated the lesson to talk about when namespaces should be used ( https://www.learncpp.com/cpp-tutorial/4-3b-namespaces/#when ). If you still have questions, please ask :)

  • Samira Ferdi

    Hi, Alex and Nascardriver!
    How you define function in namespace? Do you define all function's definition in a namespace or just the function's forward declarations and write the function's definition in separate .cpp files inside the same namespace?

    Do you do this?

    or like this in header files for function's forward declaration

    and in the separate .cpp files for function definition

  • daniel

    The reason we use namespaces is that a namespace defines an area of code in which all identifiers are guaranteed to be unique and we achieve this by using the NAME of the namespace and the scope resolution operator to use the identifer in the namespace. correct?

    But i saw on the enum chapter that apparently u can use anonymous namespaces. Whats the purpose of those when the pupose of namespaces is to make sure all identifers are unique

    • Members of unnamed namespaces have internal linkage (They can only be used in the file they're defined in) and the namespace still creates a scope.

      Unnamed namespaces are rare.

  • David Cane

    This is amazing and quite funny,I mean orange::banana.
    using function orange::banana() calling ::apple() and orange::apple().

  • madjiddex

    Hello, First of all I wanna thank you for all the efforts that you've done in this website to provide such a rich contents of Cpp in a structured way ,I have a little suggestion to you to  help people navigate easily through out the content. If you can add a side bar to all the topics in this site it's would be a great thing.

    • Alex

      Hmmm. Some of the lessons have pretty long names, so I'm not quite sure how that would fit in the sidebar. Any thoughts?

      • Avery

        Hi Alex - I would put the chapters and their subsections (i.e., this would be labeled as '4.3b' on the sidebar). I would also put a 'Next section' and 'Previous section' somewhere on the page (or sidebar) so people can easily navigate - as I am doing now.

      • Dakir Thompson

        I would love to see a side bar that stays with you as you scroll maybe it could be collapsible. that would help as of now, we have to scroll either to the top or the bottom of the page to get back to the table of contents. what I currently do is open a new tab for each section I read so I can easily go back to the table of contents. Sometime I want to remind myself of which chapter I am in or where this lesson falls in the grand scheme of things.

        But overall this site helped me get a job as a software engineer so thank you so much.

      • I don't know anything about coding for web browsers, but if it's feasible you could have the name expand on mouse-over. I'm not sure if that makes navigation any easier, though.

  • Matvey Kiselyov

    Hello. In which point of the program the compiler discovers what std is? For user-defined namespaces we should include some library or just write it in the global namespace to use this namespace. We doesn't define std namespace in the global namespace, but we can use it. How it happens?

    • Alex

      All top-level namespaces are placed in the global namespace. When you #include headers from the standard library, those headers define content that lives inside the std namespace. When we call something via std::whatever, the compiler leverages the prefix to see if there's a namespace of that name, and whether whatever is declared within it.

  • What I wonder about when it comes to namespaces, I guess they work in all files calling stuff in the namespace regardless if the namespace was in the same file or not.
    Now let's say, I use "namespace Jeroen" for all my own libraries, and suddenly I want to use a library written by my same-named-evil-twin using the same name of his namespace (in the Netherlands "Jeroen" is a VERY common name, I tell ya)... Do I have a problem now? :-P

    • Hi Jeroen!

      There's no way to tell the two libraries (Yours and the other Jeroen's) apart.
      Inevitably, the two namespaces will merge.

      You're now in the same situation you'd be in if neither of you used namespaces. If you have duplicate functions/variables/etc, you'll be unable to compile.
      One way around this is adding more namespaces to lower the chances of a collision.

      When you use your library now, you can safely use

      and access the members via

      If you happen to run into a library that's also namespaced "jeroen", you remove

      and access your library via

      If you're lucky, you and jeroen are using inline namespaces:

      Let's say you're using

      in your code and Jeroen Jansen comes along with his library

      Your call

      is now ambiguous. But you can swiftly replace every jeroen::* with jeroen::broks::* in your code and use jeroen::jansen::* to access jeroen's library without modifying either of the libraries.

      If you're willing to recompile your library you can also use the preprocessor to add a namespace into or around your existing namespace.

      This will place your library in the sub-namespace broks, iff that unique define exists.
      If you run into Jeroen Jansen now, you can recompile with

      and access your library via

      and jeroen's library via

      Out of the 3 options I'd go with inline namespaces, because they're the most convenient. They're likely to fail, because inline namespaces have added in C++17 and libraries have been around since forever.

  • Nathan

    Is there a way to make the program wait for about a second before continuing?

  • Dimitri

    Hi,

    What the difference between

    and

    ?

  • Benur21

    Is there any reason to use ::doSomething rather than doSomething?

    • Output

    • Diana

      If a function is nested inside another function and there also exists a global function having the same name as the nested function. You want to access the global function inside the nest.

  • Slim

    Can we just import "namespace" rather than importing header files that contain the namespace?

  • "when main() #included both foo.h and goo.h, both versions of doSomething() were included into the global namespace"
    main() didn't include it?  Assuming it meant main.cpp

  • Codename 47

    Hey Alex,

    In the example of multiple namespaces topic, the main.cpp file misses an #include<iostream> statement.

  • FarKiD

    Hi, in your example in this code :

    I don't understand why you used void, could someone explain please? thanks in advance

  • Hello, Alex.

    What do you think about the use of semicolons at the end of namespace definitions e.g.

    I've seen code where this is used and some where it isn't.

    • Hi Victor!

      It's non-standard. Meaning that it causes errors when compiled with most compilers. If your compiler allows it, see lesson 0.10 and 0.11 to make sure you're writing standard-conform code.

  • You wouldn't usually have two namespaces in one file.

    adding.hpp

    adding.cpp

    • Dear Mr Nas!
      Thank you for  taking your golden time to me.
      What bout header file? This is what i have been confusing  of. That means can we have to  add a .hpp file for the header with header guards like..
      #ifndef ADDING_h
      #define ADDING_H
      double add(double my_expense,double my_income);
      double add(double my_salary,double  my_bonus); //it can be a function with another identifier.
      #endif
      or the name space uses as a header guard like above?
      This my last question sir!!!
      Really sorry for the ping pong and thank you for your Patience indeed!!!!!

  • Dear Blessed teacher Mr. Alex!
    I would like to sorry in advance if my question was initially pointed out by other person.
    My question is focused on synchronization b/n namespaces,headers header's definition
    1) Is a  .h file the only place for namespace declaration? Can we declare and define namespaces in a .cpp file?

    2) for example iostream is a header for d/t forward declarations that their definition is found in run time library. what about the namespaces? are they declared in another .h file? or in side iostream header file?

    3) during  namespace declaration we have to define the function or variable with in the block of a namespace that we need it to be unique.  Can we use this definition as a definition for header's file forward declaration (prototype)  or we have to define it in a   .CPP file for 2nd time too?  

       Stay blessed with you kindness Sir!!!!!

    • Hi!

      1,2) The namespace has to be in all files that declare/define members of the namespace

      3) I don't understand

      • Dear blessed Mr Nas!!!
        Thank you so much for a very swift  response as usual .Ok just help me to do the code for the below question. I will  get my answer from that.(I believe)

        let we say we have a header file called adding.h that have 2 prototypes....
        //Prototype1)  
        double add(double my_expense,double my_income);  
        //prototype 2)  
        double add(double my_salary,double  my_bonus);  // NOTE: let we think their definition  found in another adding.CPP file.
        And they have to be unique through namespaces.  prototype 1 in namespace my_usage{}
        and ptototype 2 in namespace myGain{}
        How can we do full code for the above ?

           With a huge respect and prayer for you  sir!!!!!!!!!

  • Hi there!

    Please use code tags when sharing code.

    1. Yes
    2. The namespace has to be around both, the declaration and the definition
    3. No, the function declarations have to be in the same namespace as their definitions.

  • I, like Jesper Nielson # April 12 2018 # struggled a little with the concept of not using namespaces more having spent many years using C# to develop forms and online calculators for specific formulae. Modern C# regularly encapsulates blocks of functions and classes into a Namespace such as the following:

    C++ seems more complicated using similar naming conventions but with different restrictions on their use, or with different concepts of meaning.

    • Hi Nigel!

      Other than @main, you can, and should, store everything in some kind of structure (struct, class, namespace, ...).
      Namespaces in cpp or usually used for entire projects, eg. when writing a library. Parts of that project are stored in classes.
      For the most part, the examples on learncpp are so small that they don't need any packaging.

  • Jesper Nielsen

    As a long time C# and before that Java programmer I find it hard to understand namespaces (and folders) are not used a lot more.
    But on the other hands Visual Studio really starts fighting you if you want to arrange your code...

  • Matt

    What would be considered a rule of thumb for "best practice" when it comes to namespaces, multiple files, etc?  To clarify my question (and to highlight why I am starting to get nervous at this point in the tutorial series): Every time I write a program from this point forward, should I be separating my individual functions into their own .cpp files, should I be giving all of my functions their own namespace, making ample use of .header files, using global const variables as often as possible, et cetera in the name of practicing the concepts?  Or, in contrast, should a 'minimalist' approach be used, using as few files as necessary for disambiguation, convenience, and clarity?

    Clearly, C++ has a ton of functionality and there are several ways to accomplish the same goal.  In the last chapter or so worth of lessons we have introduced a ton of tools/concepts that seem, if you'll excuse my saying so, almost unnecessary (considering what they offer can be accomplished without them using what we've learned prior).

    Perhaps I'm writing this because I'm feeling a bit overwhelmed and instead of learning simple exercises in syntax we're being familiarized with a myriad of options/tools - thanks for your time!

    • nascardriver

      Hi Matt!

      Further down the line you'll rarely have plain functions in their own file, because almost everything will be in a class. Each class will be in it's own file. If multiple classes have something in common (eg. they're all part of the same framework) they'll be in the same namespace (One namespace can stretch across multiple files). For the most part of the tutorials here a single-file approach fits best.

      > using global const variables as often as possible
      Global things are bad, avoid them.

    • Alex

      Nascardriver's answer is good.

      For these academic programs, a single file will typically suffice just fine.

      Multiple files become far more useful when:
      * You start writing lengthy, non-trivial programs and need the additional organization that multiple files can provide.
      * You start writing programs that make use of reusable code (that reusable code should live in separate .cpp/.h files). Classes (covered in chapter 8) really help with this.

      For the most part, you won't need to use your own namespaces. They're covered more so you understand how they work, not because we expect you to be creating your own. Same with global variables -- good to know they exist, but you should generally avoid them as much as possible. :)

    • A comforting thought from Bjarne Stroustrop: "You don't have to learn all of those features to effectively use C++"...

  • nascardriver

    Hi Alex!

    I think the section "Nested namespaces and namespace aliases" could use a little C++17

  • Baljinder

    I just wanted to mention that under the 'Multiple namespace blocks with the same name allowed' section, the first sentence contains the following, "multiple places within in the same file". Perhaps, it would be clearer to say "multiple places in the same file" (i.e. without the word within).

Leave a Comment

Put all code inside code tags: [code]your code here[/code]