cconstantsdeclarationexternstdint

Defining global constants in C


How can I define a global constant in C? I was told to do some thing like this

in header.h

const u32 g_my_const;

in code.c

#include "header.h"
const u32 g_my_const= 10U;

But I get a compilation error:

error: uninitialized const 'g_my_const' [-fpermissive]

Can some one explain how to do this properly.


Solution

  • Use in the header

    extern const u32 g_my_const;
    

    In this case this will be only a declaration of the constant and in the c module there will be its definition.

    #include "header.h"
    const u32 g_my_const= 10U;
    

    As it was already mentioned in a comment by @Thomas Jager to your question you can use standard aliases for types by means of including the header <stdint.h>

    For example

    #include <stdint.h>
    
    extern const uint32_t g_my_const;