Search code examples
cinitializationglobal-variablesconstant-expressionstorage-duration

Initializer element is not a compile-time constant using C


a.h

list* FunctionNamesCreate();
list* const FunctionNames = FunctionNamesCreate();

a.c

list* FunctionCreate() {
    list* FunctionNames = listCreate(sizeof(char*));
    listPushHead(FunctionNames,"s");
    return FunctionNames;
}

list is simple void* linked list structure

When I want to create FunctionNames global variable the code editor give me the following error: a.h:8:29: error: initializer element is not a compile-time constant. If I do not use the const before FunctionNames the the code editor give me the same error.


Solution

  • This declaration

    list* const FunctionNames = FunctionNamesCreate();
    

    is a file scope declaration with static storage duration that may be initialized by a constant compile-time expression.

    From the C Standard (6.7.9 Initialization)

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

    This expression

    FunctionNamesCreate()
    

    is not a compile-time constant expression. The function call evaluates at run-time.

    From the C Standard (6.6 Constant expressions)

    3 Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated.

    There is no need to declare the pointer at a file scope. It is a bad approach moreover when you placed a pointer definition with external linkage in a header. Declare the pointer for example in main.