Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining global constant in C++

Tags:

c++

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_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;

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

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

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

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

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

  1. What do you prefer (5) or (6)?
  2. Why (5) is ok, while (2) is not?
like image 654
dimba Avatar asked Feb 15 '10 20:02

dimba


People also ask

Can we define global variable in C?

The variables that are declared outside the given function are known as global variables. These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables.

How do you define constant in C?

A constant is a name given to the variable whose values can't be altered or changed. A constant is very similar to variables in the C programming language, but it can hold only a single variable during the execution of a program.

What is a global constant?

Global Constants. A global constant is a literal value to which you assign a name. Like a global variable, you can access the value of the global constant from any script or 4GL procedure in the application. You set the value for the global constant when you declare it.


1 Answers

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; 
like image 183
Nikolai Fetissov Avatar answered Oct 13 '22 06:10

Nikolai Fetissov