在C ++中定义全局常量 [英] Defining global constant in C++

查看:127
本文介绍了在C ++中定义全局常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中定义一个在多个源文件中可见的常量。
我可以通过以下方式在头文件中定义它:

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


  1. #define GLOBAL_CONST_VAR 0xFF

  2. int GLOBAL_CONST_VAR = 0xFF;

  3. (例如 int get_GLOBAL_CONST_VAR()

  4. 枚举{GLOBAL_CONST_VAR = 0xFF; }

  5. const int GLOBAL_CONST_VAR = 0xFF;

  6. code> extern const int GLOBAL_CONST_VAR;
    和一个源文件 const int GLOBAL_CONST_VAR = 0xFF;

  1. #define GLOBAL_CONST_VAR 0xFF
  2. int GLOBAL_CONST_VAR = 0xFF;
  3. Some function returing the value (e.g. int get_GLOBAL_CONST_VAR())
  4. enum { GLOBAL_CONST_VAR = 0xFF; }
  5. const int GLOBAL_CONST_VAR = 0xFF;
  6. extern const int GLOBAL_CONST_VAR; and in one source file const int GLOBAL_CONST_VAR = 0xFF;

选项(1) - 绝对不是您要使用的选项

Option (1) - is definitely not the option you would like to use

选项2) - 使用头文件定义每个目标文件中的变量实例

Option (2) - defining instance of the variable in each object file using the header file

选项(3) - IMO在大多数情况下过度杀死

Option (3) - IMO is over killing in most cases

选项(4) - 在许多情况下可能不好,因为枚举没有具体类型(C ++ 0X将增加定义类型的可能性)

Option (4) - in many cases maybe not good since enum has no concrete type (C++0X will add possibility to define the type)

所以在大多数情况下,我需要在(5)和(6)之间进行选择。
我的问题:

So in most cases I need to choose between (5) and (6). My questions:


  1. 您更喜欢(5)还是(6)?

  2. 为什么(5)是好的,而(2)不是?


推荐答案

5)说出你想说的话。此外,它允许编译器大部分时间优化它。 (6)另一方面不会让编译器优化它,因为编译器不知道你是否会最终改变它。

(5) says exactly what you want to say. Plus it lets the compiler optimize it away most of the time. (6) on the other hand won't let the compiler ever optimize it away because the compiler doesn't know if you'll change it eventually or not.

这篇关于在C ++中定义全局常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆