3

I have a small project and all its code is in one namespace (multiple files), in certain file I need to use multiple constants.

Only this one file will use those constant variables.

Which one is the right way to go and what's the difference (I'm familiar with static and const but still don't know the difference)

  1. declare static const in the header, define in the source file
  2. define const in source file in the namespace scope
  3. define static const in source file in the namespace scope
zonzor18
  • 63
  • 6

2 Answers2

0

Only this one file will use those constant variables.

If I understood correctly, that sentence automatically excludes the first option:

declare static const in the header, define in the source file

You don't need to expose the declaration in other compilation units (cpp files), so you don't need a header file includable in different cpp files.


At this point the following options:

  1. define const in source file in the namespace scope

  2. define static const in source file in the namespace scope

In your situation, the correct answer should be (3).


Why?

The answer is simply the correlation with the meaning of static variable outside function block.

From here:

The static specifier [...]. When used in a declaration at namespace scope, it specifies internal linkage.

So when you need to declare a constant variable which will be used only in that single compilation unit (cpp file), you should declare it as static const in order to express the internal linkage more explicit in the reading.


Extra

In general is a good point to use, instead, an anonymous namespace in your compilation unit.

In your .cpp file:

 namespace {
    const int kVariable = 12;
 }

 // no more static const int kVariable = 12;

 void foo() {
   std::cout << kVariable << '\n';
 }

The purpose is practically the same.


Conclusions

All those information give you a general idea about static keyword in the constant declarations.

Anyway, it is often a matter of style.

Community
  • 1
  • 1
BiagioF
  • 9,368
  • 2
  • 26
  • 50
0

I'd select option #3. It is a little more typing, and means the same thing as #2.

But people (myself included!) can easily forget that a const will have internal linkage unless declared extern const. So putting static const helps with self-documenting code, in my opinion.

If you like anonymous namespaces, you could put them in one to help clarify that they are internal to that translation unit. That is a matter of preference.

Eljay
  • 4,648
  • 3
  • 16
  • 27