In lesson 2.8 -- 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:
1 2 3 4 5 |
// This doSomething() adds the value of its parameters int doSomething(int x, int y) { return x + y; } |
goo.cpp:
1 2 3 4 5 |
// This doSomething() subtracts the value of its parameters int doSomething(int x, int y) { return x - y; } |
main.cpp:
1 2 3 4 5 6 7 8 9 |
#include <iostream> int doSomething(int x, int y); // forward declaration for doSomething int main() { std::cout << doSomething(4, 3) << '\n'; // which doSomething will we get? return 0; } |
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:
1 2 3 4 5 6 7 8 |
namespace foo // define a namespace named foo { // This doSomething() belongs to namespace foo int doSomething(int x, int y) { return x + y; } } |
goo.cpp:
1 2 3 4 5 6 7 8 |
namespace goo // define a namespace named goo { // This doSomething() belongs to namespace goo int doSomething(int x, int y) { return x - y; } } |
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:
1 2 3 4 5 6 7 |
int doSomething(int x, int y); // forward declaration for doSomething int main() { std::cout << doSomething(4, 3) << '\n'; // which doSomething will we get? return 0; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> namespace foo // define a namespace named foo { // This doSomething() belongs to namespace foo int doSomething(int x, int y) { return x + y; } } namespace goo // define a namespace named goo { // This doSomething() belongs to namespace goo int doSomething(int x, int y) { return x - y; } } int main() { std::cout << foo::doSomething(4, 3) << '\n'; // use the doSomething() that exists in namespace foo return 0; } |
This produces the expected result:
7
If we wanted to use the version of doSomething()
that lives in goo
instead:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> namespace foo // define a namespace named foo { // This doSomething() belongs to namespace foo int doSomething(int x, int y) { return x + y; } } namespace goo // define a namespace named goo { // This doSomething() belongs to namespace goo int doSomething(int x, int y) { return x - y; } } int main() { std::cout << goo::doSomething(4, 3) << '\n'; // use the doSomething() that exists in namespace goo return 0; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> namespace foo // define a namespace named foo { // This doSomething() belongs to namespace foo int doSomething(int x, int y) { return x + y; } } namespace goo // define a namespace named goo { // This doSomething() belongs to namespace goo int doSomething(int x, int y) { return x - y; } } 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; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> void print() // this print lives in the global namespace { std::cout << " there\n"; } namespace foo { void print() // this print lives in the foo namespace { std::cout << "Hello"; } } int main() { foo::print(); // call foo::print() ::print(); // call print() in global namespace (same as just calling print() in this case) return 0; } |
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:
1 2 3 4 5 6 7 8 9 |
#ifndef CIRCLE_H #define CIRCLE_H namespace basicMath { inline constexpr double pi{ 3.14 }; } #endif |
growth.h:
1 2 3 4 5 6 7 8 9 10 |
#ifndef GROWTH_H #define GROWTH_H namespace basicMath { // the constant e is also part of namespace basicMath inline constexpr double e{ 2.7 }; } #endif |
main.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include "circle.h" // for basicMath::pi #include "growth.h" // for basicMath::e #include <iostream> int main() { std::cout << basicMath::pi << '\n'; std::cout << basicMath::e << '\n'; return 0; } |
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
1 2 3 4 5 6 7 8 9 10 |
#ifndef ADD_H #define ADD_H namespace basicMath { // function add() is part of namespace basicMath int add(int x, int y); } #endif |
add.cpp
1 2 3 4 5 6 7 8 9 10 |
#include "add.h" namespace basicMath { // define the function add() int add(int x, int y) { return x + y; } } |
main.cpp
1 2 3 4 5 6 7 8 9 10 |
#include "add.h" // for basicMath::add() #include <iostream> int main() { std::cout << basicMath::add(4, 3) << '\n'; return 0; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> namespace foo { namespace goo // goo is a namespace inside the foo namespace { int add(int x, int y) { return x + y; } } } int main() { std::cout << foo::goo::add(1, 2) << '\n'; return 0; } |
Note that because namespace goo
is inside of namespace foo
, we access add
as foo::goo::add
.
Since C++17, nested namespaces can also be declared this way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> namespace foo::goo // goo is a namespace inside the foo namespace (C++17 style) { int add(int x, int y) { return x + y; } } int main() { std::cout << foo::goo::add(1, 2) << '\n'; return 0; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> namespace foo::goo { int add(int x, int y) { return x + y; } } int main() { namespace boo = foo::goo; // boo now refers to foo::goo std::cout << boo::add(1, 2) << '\n'; // This is really foo::goo::add() return 0; } // The boo alias ends here |
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.
![]() |
![]() |
![]() |
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.
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.
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. :)
No, functions belonging to a namespace must be defined inside the namespace block.
"You can still get naming collisions with using declarations:"
should be
"You can still get naming collisions with using directives:"
Thanks, fixed.
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 ?
> 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.
Thanks, will do
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.
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.
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
Good idea. I'll start a collection.
Upvote for the suggestion. For some time I was thinking about making one myself. Now you are doing it, it would help if you post a link directly on the home page, once it is finished. Thanks in advance, Alex. :)
Alex,
Looks good to me. Thanks
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.
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?
How can i use namespace within multiple location??
Thnx in advance!
The subsection titled "Multiple namespace blocks with the same name allowed" in the lesson above has an example. Is something not clear?
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)
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.
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 ?!
What does a "local area" mean in this context? It's unclear.
I mean a block.
A namespace can be defined over multiple blocks, so defining it as "a block" would be inaccurate.
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 ?
Good question. Local variables aren't considered part of the global namespace. They're local to the block they are declared in.
Thanks a lot!!!
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 ;)
> 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.
Is the following program correct
foo.cpp
foo.h
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
It isn't working still it is giving an error and how can you save two files with the same name.
I made a couple of typos that I just fixed. Try again. I tested it, it works fine for me.
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)?
The global namespace is essentially what we call everything that isn't in a different namespace.
Yes, you can explicitly call Foo::doSomething().
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)"
Good call. Updated. Thanks!
If the two Alex’s were in different classrooms...
what about Alex's? should it not be Alexes(it should)?
Todd is getting slacky ;) or there was a latter edition
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.
Yes. Good catch. I've fixed the example.
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.
Good idea! I'll incorporate that into the quizzes. Thanks for the suggestion.
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.
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 :)
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.
nice work!!
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.
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
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.
Thank you for the explanation. Got it now :) .
my question
No. The std namespace was declared this like:
namespace std
{
// lots of stuff
}
Just like all of the other named namespaces.
question
is "int main(void)" and "int main()" the same thing?
yes!
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().
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().
What about 'namespace pollution'? You should never 'use' a namespace in a header file.
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:
Thanks.
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.
Nope, not omitted on purpose. I've updated the lesson to include information on namespace aliases, as well as nested namespaces.