C compiler error - initializer is 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 as follows:

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

However, the following compilation error occurs on this line:

Error: initializer element not constant

Why is this happening? 10 and 1 are obviously constants that should not bother malloc , etc. The code is pre c99 C.

Only the -Wall flag.

thanks

+4
source share
2 answers

You can only initialize global variables in your declaration with a constant value, which newGQueue not.

This is because all global variables must be initialized before the program can begin execution. The compiler takes any constant values ​​assigned to global variables when they are declared, and uses this value in the OS loader when the program starts.

Just initialize your kbdQueue when declaring NULL and initialize it with a value in the main or other startup function.

 volatile GQueue * kbdQueue = NULL; int main() { kbdQueue = newGQueue(10,1); } 
+7
source

The problem is not with the arguments for newGQueue, it is using the return value of newGQueue to initialize kbdQueue. This executable code and in C all initializers must be known at compile time. This is a problem only for C; C ++ would accept it without a problem.

If you expand the declaration and initialization, it should work fine.

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

Source: https://habr.com/ru/post/1332372/


All Articles