4

I have a dedicated HW register header file, I have created a namespace, like this, which holds all of my HW register addresses:

namespace{
 const uint32_t Register1                    = (0x00000000);
 const uint32_t Register2                    = (0x00000004);
 const uint32_t Register3                    = (0x00000008);
 const uint32_t Register4                    = (0x0000000c);
}

Is this considered better than using:

 static const uint32_t Register1             = (0x00000000);
 static const uint32_t Register2             = (0x00000004);
 static const uint32_t Register3             = (0x00000008);
 static const uint32_t Register4             = (0x0000000c); 

I guess the point of namespaces is that we don't pollute the global namespace. Is that right?

I have one .cpp, which uses the header file.

ElGavilan
  • 6,610
  • 16
  • 27
  • 36
user1876942
  • 1,411
  • 2
  • 20
  • 32

2 Answers2

5

The two are essentially equivalent.

The global-static method was deprecated in C++03 ([depr.static]) in favour of unnamed namespaces, but then undeprecated by C++11 because everybody realised there is no objective benefit of one over the other in the general case.

However, for this, you may find an enum or enum class to be more manageable and idiomatic.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
3

These two are 100% equivalent, and they're also 100% equivalent to omitting both namespace and static:

const uint32_t Register1                    = (0x00000000);
const uint32_t Register2                    = (0x00000004);
const uint32_t Register3                    = (0x00000008);
const uint32_t Register4                    = (0x0000000c);

The reason is simple - a const variable is static unless you explicitly declare it extern.

However, this looks like something where using an enumeration would be preferable.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455