Skip to content

Latest commit

 

History

History
48 lines (39 loc) · 1.16 KB

global.md

File metadata and controls

48 lines (39 loc) · 1.16 KB

Global Variables in C++

Global variables should generally be avoided, because they are available everywhere. It is difficult to understand where they are modified and used. However, if you really need them:

Small Constants

// header, or source (add static)
constexpr int x = 0;

Use const for non-literal types.

Extern (Header File)

?inline

// header
extern int x;

Extern (Source File)

?inline

// source
int x = 0;

Inline (since C++17)

// header only, use static in source
inline int x = 0;

General Advice

?inline Use static or an unnamed namespace for any globals that are TU-local (used only in one cpp file).

Common Mistake

?inline If you put int x = 0; into a header, you may get linker errors. x is extern by default, so the linker would see multiple conflicting definitions when the header is included in multiple source files.

Also See

<:cppreference:875716540929015908> Storage class specifiers