Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do statics need a class?

Tags:

c++

static

I've actually never tried it until now. Is it possible to have statics just in namespace scope without a class? Why not?

namespace MyNamespace
{
  static int a;
}

assign something, somewhere else....
like image 747
jeromintus Avatar asked Sep 29 '22 02:09

jeromintus


1 Answers

Annex D (Compatibility features) [C++03]

D2: The use of the static keyword is deprecated when declaring objects in namespace scope.

static variable at namespace scope (global or otherwise) has internal linkage. That means, it cannot be accessed from other translation units. It is internal to the translation unit in which it is declared.

update
When you declare a variable as static, it means that its scope is limited to the given translation unit only. Without static the scope is global.

When you declare a variable as static inside a .h file (within or without namespace; doesn't matter), and include that header file in various .cpp files, the static variable becomes locally scoped to each of the .cpp files. So now, every .cpp file that includes that header will have its own copy of that variable.

Without the static keyword the compiler will generate only one copy of that variable, so as soon as you include the header file in multiple .cpp files the linker will complain about multiple definitions.

like image 100
tema Avatar answered Oct 06 '22 02:10

tema