“初始化程序不恒定”的全局变量? [英] 'Initializer not constant' on global variable?

查看:210
本文介绍了“初始化程序不恒定”的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我编译如下code时,你得到初始元素不是常量错误:

So I get the 'initializer element not constant' error when compiling the following code:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

float wl = 2.0f;
float k = 2.0f * (float) M_PI / wl;

int main ()
{
     //Do stuff
}

如果我移动浮动K的主要方法里面,有​​没有错误,但是这不是我的选择,因为我需要浮动K将是一个全局变量。即使我把它改成这样:

If I move "float k" inside the main method, there's no errors, but this isn't an option for me, because I NEED float k to be a global variable. Even if I change it to this:

const float wl = 2.0f;
const float k = 2.0f * (float) M_PI / wl;

错误仍然发生。我该如何解决这个问题?

the error still happens. How do I fix this?

推荐答案

全球静态变量存储在当初始化数据段(DS)和块开始由符号(BSS)时初始化。这些变量有一个固定的内存位置和内存在编译时分配的。结果
C不会允许与非常数值全局值初始化。

Global and static variables are stored in Data Segment(DS) when initialized and Block Start by Symbol(BSS) when uninitialized. These variables have a fixed memory location and memory is allocated in compile time .
C does not allow initialization of global values with non constant values.

C99 Standard: Section 6.7.8:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

您需要移动初始化中的宣布保持随着全球

You need to move the initialization inside the main keeping declaration as global

float wl = 2.0f;
float k  ;

int main ()
{
      k = 2.0f * (float) M_PI / wl;
     //Do stuff
}

这篇关于“初始化程序不恒定”的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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