Home > Software design >  How do I define static constants using other extern constants in its definition?
How do I define static constants using other extern constants in its definition?

Time:11-03

I've been trying to create static consts using extern consts declared in an included .h file and defined in an associated .c file. However the compiler complains that the initializer element is not constant, as if the extern invalidated constants. So I was wondering if there was a way to use these extern consts in the definition of other consts without this error.

Here's the code:

consts.c

const float G = 6.67408E-11;
const int metre = 10;
const int window_width = 500;
const int window_height = 500;
const float seconds_per_frame = 1.0f/60.0f;
const float frames_per_second = 60.0f;

consts.h

extern const float G;
extern const int metre;
extern int window_width;
extern const int window_height;
extern const float seconds_per_frame;
extern const float frames_per_second;

particle.c

#include "../constants/consts.h"

static const float max_position_x = window_width; 
static const float max_position_y = window_height; //Errors in these three statements
static const float max_speed = 5 * metre;          //"initializer element is not constant"
(...)

And before you ask, I have linked with consts.c and can use any of the consts defined there inside particle.c no problem. It's just trying to use them for consts that causes an error.

CodePudding user response:

In C, variables declared at file scope may only be initialized with a constant expression, which loosely speaking means a compile time constant. A variable declared as const is not considered a constant expression, so it cannot be used to initialize file scope variables.

The way around this is to use #define macros for these values instead. A macro does direct token substitution so that they may be used where a constant expression is required.

So your header file would contain this:

#define G 6.67408E-11
#define metre 10
#define window_width 500
#define window_height 500
#define seconds_per_frame (1.0f/60.0f)
#define frames_per_second 60.0f

And consts.c would not be necessary.

  •  Tags:  
  • c gcc
  • Related