Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C compiler error - initializer not constant

I have a function used to create a new 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.

Only flag is -Wall.

Thanks

like image 276
F. P. Avatar asked Dec 29 '22 03:12

F. P.


1 Answers

You can only initialize global variables at their declaration with a constant value, which newGQueue is not.

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.

Just initialize your kbdQueue at declaration to NULL and initialize it to a value in main or other startup function.

volatile GQueue * kbdQueue = NULL;

int main() {
    kbdQueue = newGQueue(10,1);
}
like image 68
joshperry Avatar answered Jan 11 '23 02:01

joshperry