Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue : Initializer element is not constant on C #define

I am using a #define to call a function and get the following gcc error:
"error: initializer element is not constant" on the directive.

Here, the define directive:

#define HASH(STRING_VALUE) (lookup_hash(STRING_VALUE))

Function implementation:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

static inline uint32_t lookup_hash(const char *str)
{
    uint32_t hash = 5381;
    int32_t c;

    while ((c = *str++))
    {
        hash = ((hash << 5) + hash) + c;
    }

    return hash;
}

Function call example:

static const asr_handlerTree_t asr_LT_nwk_orders[]=
{
    {HASH("link"), NULL, asr_link_funct},
    {HASH("unlink"), NULL, asr_unlink_funct},

    //  Used at runtime to determinate table limit, keep at table tail
    {(uint32_t) 0, NULL, NULL}
};

Why gcc compiler raise the issue as directive calls should only be replaced by function at pre-processing ?


Update: Add structure declaration following answer feedbacks:

typedef struct _asr_handlerTree_type_
{
    const uint32_t hashedIntent_u32;
    const asr_handlerTree_t * branchs;
    const funct_t Func;
} asr_handlerTree_t;

>Solution :

Variables with static storage duration, i.e. those declared at file scope or with the static keyword, can only be initialized with constant expressions. This means you can’t use the values of other variables (although you can use their addresses) or make function calls.

You would need to initialize this particular field with a dummy value, then have a function that is called at the start of main that assigns the values that need to be set at runtime.

static const asr_handlerTree_t asr_LT_nwk_orders[]=
{
    {0, NULL, asr_link_funct},
    {0, NULL, asr_unlink_funct},

    //  Used at runtime to determinate table limit, keep at table tail
    {(uint32_t) 0, NULL, NULL}
};

void set_hashes()
{
    asr_LT_nwk_orders[0].hash = HASH("link");
    asr_LT_nwk_orders[1].hash = HASH("unlink");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading