We can create custom namespaces using namespace keyword as shown below.
#include "../helpers/stdout.h"
namespace Constants
{
constexpr double pi{3.14};
}
int main(int argc, char const *argv[])
{
print(Constants::pi);
return 0;
}Constants is a namespace containing pi constant expression. We need to use scope resolution operator :: to access values inside a namespace.
Namespaces in multiple files setup
If we have multiple file setup, we need to use namespace in header files for forward declarations, as shown below.
main.cpp
#include "../helpers/stdout.h"
#include "math.h"
int add(int a, int b)
{
return a + b + 10;
}
int main(int argc, char const *argv[])
{
print(Math::add(1, 2));
print(Math::increment(1));
print(add(1, 2));
print(::add(1, 2));
return 0;
}math.cpp
namespace Math
{
int add(int a, int b)
{
return a + b;
}
int increment(int a)
{
return add(a, 1);
}
}And finally header file for math.
math.h
#ifndef MATH_H
#define MATH_H
namespace Math
{
int add(int, int);
int increment(int);
}
#endifNow compiler would be happy to compile to program as it can find the forward declaration for the function and linker can find the definition. We can use following command to compile the program.
clang++ -ggdb -std=c++20 main.cpp ../helpers/stdout.cpp math.cpp -o main.out
Multiple same namespaces
We can define multiple same namespaces. All the declarations are considered part of the namespace.
namespace Constants
{
constexpr double pi{3.14};
}
namespace Constants
{
constexpr double light{3e8};
}
int main(int argc, char const *argv[])
{
print(Constants::light);
print(Constants::pi);
return 0;
}Both constants are part of the namespace Constants. This way, we also add more declarations to already existing namespaces.
Warning
Adding custom functionalities to
stdnamespace causes undefined behavior as it has some special rule that prohibits extension from user code.