C ++ namespace and static variables

I have a requirement when a variable (const) must be available in all cpp consisting of several classes. I decided to use a namespace to solve the problem, but am not sure of the following:

  • Is it necessary to define this variable as static?
  • Is it true that I can avoid turning the variable static only if I go over with an unnamed namespace?
+6
source share
1 answer
  • You do not need to define the variable as static or in an anonymous namespace. However, if you are not using this object outside the file specified in it, it is a good idea to reduce namespace pollution and speed up links (by reducing the number of characters that the linker needs to consider).
  • If you declare a variable in an anonymous namespace, it will be effectively static. There is no need to actually make it static (although you can if you want). The advantage of anonymous namespaces is that you can also define types (classes, structures, enumerations, typedefs), as well as static variables and functions.
+6
source

Source: https://habr.com/ru/post/904004/


All Articles