2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Mohamed Hossam
  • 33
  • 1
  • 1
  • 4
  • 4
    Don't define variables (even `const`) in `h` files. `extern` them there. The rule of thumb - if it is creating an object in memory - it should not be in the header. – Eugene Sh. Jul 26 '19 at 14:16
  • 2
    As another note, unless you're stuck supporting code that targets an implementation without it, you should use fixed-size integer types from `` instead of custom ones. (Unless, like me, you're stuck maintaining code written by people too stubborn to use that and they decided to write their own header for it anyways.) – Thomas Jager Jul 26 '19 at 14:19
  • Thanks for the info and yes I am stuck with a legacy architecture that I had to keep, I don't have much room for innovation here :) – Mohamed Hossam Jul 26 '19 at 14:27
  • See also [“static const” vs “#define” vs “enum”](https://stackoverflow.com/questions/1674032/static-const-vs-define-vs-enum). – Jonathan Leffler Jul 26 '19 at 20:08

1 Answers1

9

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;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Ok Thanks a lot, this makes more sense to me – Mohamed Hossam Jul 26 '19 at 14:28
  • Why doesn't `/*header.h*/ extern const unsigned g_my_const; /*EOF*/ /*example.c*/ #include "header.h" /*EOL*/ const unsigned copy = g_my_const; */EOF/*` compile? `gcc -std=c89 -c example.c` says, `error: initializer element is not constant` and indicates `g_my_const` as the culprit. (If I _define_ `g_my_const` just after the `#include`, it compiles---but I want to define that object in it's own translation unit---if possible). – Ana Nimbus Sep 23 '20 at 02:18
  • 1
    @AnaNimbus Variables with the static storage duration shall be initialized by compile-time constants. g_my_const in C is not a compile-time constant. – Vlad from Moscow Sep 23 '20 at 07:05
  • @VladfromMoscow "compile-time constant" meaning that the compiler knows what the value is, not merely that it knows that the value is `const`, right? – Ana Nimbus Sep 23 '20 at 12:41
  • @AnaNimbus There is a strict definition of such a constant. But in general you are right. – Vlad from Moscow Sep 23 '20 at 19:11