简体   繁体   English

C编译器错误 - 初始化程序不是常量

[英]C compiler error - initializer not constant

I have a function used to create a new GQueue 我有一个用于创建新GQueue

GQueue* newGQueue(int n_ele, int ele_size)
{
    GQueue* q = (GQueue*) malloc(sizeof(GQueue));
    if(!q) return NULL;

    q->ptr = malloc(n_ele * ele_size);
    if(!(q->ptr))
    {
        free(q);
        return NULL;
    }

    q->in = q->out = q->count = 0;
    q->size = n_ele; q->ele_size = ele_size;

    return q;
}

I use it like this: 我这样使用它:

volatile GQueue * kbdQueue = newGQueue(10, 1);

However, the following compilation error occurs at this line: 但是,此行发生以下编译错误:

Error: initializer element not constant

Why does this happen? 为什么会这样? 10 and 1 are obviously constants which shouldn't bother malloc , etc in pre c99 C code. 10和1显然是常量,不应该在前c99 C代码中打扰malloc等。

Only flag is -Wall . 只有标志是-Wall

Thanks 谢谢

You can only initialize global variables at their declaration with a constant value, which newGQueue is not. 您只能使用常量值在其声明中初始化全局变量,而newGQueue则不是。

This is because all global variables must be initialized before a program can begin execution. 这是因为在程序开始执行之前必须初始化所有全局变量。 The compiler takes any constant values assigned to globals at their declaration and uses that value in the program's data segment which is loaded directly into memory by the OS loader when the program is run. 编译器在其声明中获取分配给全局变量的任何常量值,并在程序的数据段中使用该值,该数据段在程序运行时由OS加载程序直接加载到内存中。

Just initialize your kbdQueue at declaration to NULL and initialize it to a value in main or other startup function. 只需在声明时将kbdQueue初始化为NULL,并将其初始化为main或其他启动函数中的值。

volatile GQueue * kbdQueue = NULL;

int main() {
    kbdQueue = newGQueue(10,1);
}

The problem is not in the arguments for newGQueue, is for using the newGQueue return value to initialize kbdQueue. 问题不在于newGQueue的参数,而是使用newGQueue返回值来初始化kbdQueue。 That's executable code, and in C all initializers have to be known at compile time. 这是可执行代码,在C中,必须在编译时知道所有初始化程序。 This is a problem in C only; 这只是C中的一个问题; C++ would accept it without problems. C ++会毫无问题地接受它。

If you break apart the declaration and initialization it should work OK. 如果你拆分声明和初始化它应该工作正常。

volatile GQueue * kbdQueue;
kbdQueue = newGQueue(10, 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM