On Programming

A discussion of programming strategies and results

Double Colon and Accessing the Global Namespace

| Comments

Recently I’ve been seeing a lot of code that accesses variables and functions that start with ::. I didn’t know what that meant, and information online seemed scant, so I decided to test it myself. Luckily, my first guess was right and it is a way to access the global namespace. One easy way to think about it is in Unix paths, if you start with a / it accesses the root the of the filesystem, whereas if you don’t then its a relative path starting from where you currently are in the folder structure.

To test this I created three files:

a.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
  #include "header.h"

  using namespace std;

  namespace a
  {
      void print_a()
      {
          cout << "a\n";
      }
  }

  int main(int argc, char** argv)
  {
      a::print_a();
      b::print_b_local();
      b::print_b_global();
  }
b.cpp
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>
  #include "header.h"

  using namespace std;

  namespace b
  {
      void print_b_global()
      {
          cout << "b ";
          ::a::print_a();
      }
      void print_b_local()
      {
          cout << "b ";
          a::print_a();
      }

      namespace a
      {
          void print_a()
          {
              cout << "b::a\n";
          }
      }
  }
header.h
1
2
3
4
5
6
7
8
9
10
11
12
13
  namespace a
  {
      void print_a();
  }
  namespace b
  {
      void print_b_global();
      void print_b_local();
      namespace a
      {
          void print_a();
      }
  }
When run I get the output:
1
2
3
4
5
6
  $ $CXX a.cpp b.cpp
  $ ./a.out
  a
  b b::a
  b a
  $ 
As you can see, without the :: preceding the function name, the compiler will search the current namespace (think current directory). With the :: the compiler will jump to the global namespace (think / on a Unix system).

Comments