Defining global constant in C++

前端 未结 10 1914
梦如初夏
梦如初夏 2020-11-29 16:44

I want to define a constant in C++ to be visible in several source files. I can imagine the following ways to define it in a header file:

  1. #define GLOBAL_
10条回答
  •  臣服心动
    2020-11-29 17:05

    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 
    int value = constants::GLOBAL_CONST_VAR;
    

提交回复
热议问题