Defining global constant in C++

Definitely go with option 5 – it’s type safe and allows compiler to optimize (don’t take address of that variable 🙂 Also if it’s in a header – stick it into a namespace to avoid polluting the global scope:

// header.hpp
namespace constants
{
    const int GLOBAL_CONST_VAR = 0xFF;
    // ... other related constants

} // namespace constants

// source.cpp - use it
#include <header.hpp>
int value = constants::GLOBAL_CONST_VAR;

Leave a Comment