6

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?
3
  • Have you tried declaring it on top, outside the classes / functions? (without static ofc) Commented Dec 18, 2011 at 3:54
  • 2
    Is there a reason you want to avoid making it static? Commented Dec 18, 2011 at 3:55
  • 1
    If it is const it is also implicitly static. You have to use extern const to make it non-static. Commented Dec 18, 2011 at 10:17

1 Answer 1

8
  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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.