简体   繁体   中英

C++ namespace and static variables

I have a requirement where a (const) variable should be available throughout an entire cpp which consists of several classes. I have decided to use a namespace to solve the problem, but unsure about the following:

  • Do I need to define this variable as static?
  • Is it true that I can avoid making the variable static only if I go with an unnamed namespace?
  1. You don't need to define the variable as static, or in an anonymous namespace. However, if you're not using this object outside of the file it's defined in, it's a good idea, to reduce namespace pollution and speed up links (by reducing how many symbols need to be considered by the linker).
  2. If you declare a variable in an anonymous namespace, it will be effectively static. There's no need to actually make it static as well (although you can if you like). The advantage of anonymous namespaces is you can also define types (classes, structs, enums, typedefs) as well as static variables and functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM