【问题标题】:How do I define static constants using other extern constants in its definition?如何在其定义中使用其他外部常量来定义静态常量?
【发布时间】:2021-12-17 11:41:43
【问题描述】:

我一直在尝试使用在包含的 .h 文件中声明并在关联的 .c 文件中定义的外部常量来创建静态常量。但是编译器抱怨初始化元素不是常量,就好像 extern 使常量无效。所以我想知道是否有办法在其他 const 的定义中使用这些 extern const 而不会出现此错误。

代码如下:

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;

粒子.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 中定义的任何 const 没有问题。它只是试图将它们用于导致错误的常量。

【问题讨论】:

  • 非常有帮助,谢谢!。我不知道如何解决我的问题。我想从 consts.h 中定义的那些常量初始化particle.c 中的这些常量。
  • "我一直在尝试使用 extern consts 创建静态 consts" 这没有任何意义,staticextern 几乎是彼此的对立面。这就像说“我想通过将这个项目外包给外部顾问来在内部完成这个项目”。在使用此代码进行任何其他操作之前,您应该研究 staticextern

标签: c gcc


【解决方案1】:

在 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 不是必需的。

【讨论】:

  • 甜蜜!多谢!我不知道像这样跨文件携带的宏...
  • @Ianvos 是的,只要您#include 另一个文件,它的行为就好像另一个文件被复制/粘贴在该位置。
猜你喜欢
  • 1970-01-01
  • 2016-07-14
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 2014-07-02
相关资源
最近更新 更多