Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 828
s.d Avatar asked Dec 18 '11 03:12

s.d


People also ask

Are namespace variables static?

By default, an object or variable that is defined in the global namespace has static duration and external linkage. The static keyword can be used in the following situations.

Are there static variables in C?

Syntax and Use of the Static Variable in COne can define a static variable both- outside or inside the function. These are local to the block, and their default value is always zero. The static variables stay alive till the program gets executed in the end.

How are static variables stored in C?

The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).

Can a namespace have a variable?

With functions: • When a function is called, a namespace for its variables is created. The function's parameters and any variables defined inside the function are placed into the function call's namespace. Variables in one namespace have NOTHING to do with variables of the same name in another namespace.


1 Answers

  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.
like image 158
bdonlan Avatar answered Sep 20 '22 06:09

bdonlan