如何在其定义中使用其他外部常量来定义静态常量?
How do I define static constants using other extern constants in its definition?
我一直在尝试使用在包含的 .h 文件中声明并在关联的 .c 文件中定义的外部常量来创建静态常量。然而,编译器抱怨初始化元素不是常量,就好像 extern 使常量无效一样。所以我想知道是否有一种方法可以在其他常量的定义中使用这些外部常量而不会出现此错误。
代码如下:
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"
(...)
在你问之前,我已经链接到 consts.c 并且可以使用 particle.c 中定义的任何常量,没问题。它只是试图将它们用于导致错误的常量。
在 C 语言中,在文件范围内声明的变量只能用 常量表达式 初始化,宽泛地说就是编译时常量。声明为 const
的变量不被视为常量表达式,因此不能用于初始化文件范围变量。
解决这个问题的方法是对这些值使用 #define
宏。宏进行直接标记替换,以便可以在需要常量表达式的地方使用它们。
因此您的头文件将包含以下内容:
#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
而consts.c则没有必要。
我一直在尝试使用在包含的 .h 文件中声明并在关联的 .c 文件中定义的外部常量来创建静态常量。然而,编译器抱怨初始化元素不是常量,就好像 extern 使常量无效一样。所以我想知道是否有一种方法可以在其他常量的定义中使用这些外部常量而不会出现此错误。
代码如下:
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"
(...)
在你问之前,我已经链接到 consts.c 并且可以使用 particle.c 中定义的任何常量,没问题。它只是试图将它们用于导致错误的常量。
在 C 语言中,在文件范围内声明的变量只能用 常量表达式 初始化,宽泛地说就是编译时常量。声明为 const
的变量不被视为常量表达式,因此不能用于初始化文件范围变量。
解决这个问题的方法是对这些值使用 #define
宏。宏进行直接标记替换,以便可以在需要常量表达式的地方使用它们。
因此您的头文件将包含以下内容:
#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
而consts.c则没有必要。