3

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.

4
  • 6
    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. Commented Jul 26, 2019 at 14:16
  • 3
    As another note, unless you're stuck supporting code that targets an implementation without it, you should use fixed-size integer types from <stdint.h> 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.) Commented Jul 26, 2019 at 14:19
  • 1
    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 :) Commented Jul 26, 2019 at 14:27
  • See also “static const” vs “#define” vs “enum”. Commented Jul 26, 2019 at 20:08

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

5 Comments

Ok Thanks a lot, this makes more sense to me
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).
@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.
@VladfromMoscow "compile-time constant" meaning that the compiler knows what the value is, not merely that it knows that the value is const, right?
@AnaNimbus There is a strict definition of such a constant. But in general you are right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.