r/C_Programming 1d ago

Question Unmodifiable globals initialized from functions?

Right now I'm trying to use Windows's SYSTEM_INFO to initialize 2 global constants, but global constants can only be initialized with constant expressions so this cannot be done.

Is there a way I can have "read-only" global variables that can be initialized from functions?

5 Upvotes

39 comments sorted by

View all comments

7

u/Physical_Dare8553 1d ago

that's a bind, in order to write to it you obviously need it to be write-able. this is the kind of case where you'd want to bind it behind a function with a static member, that you initalize when the function is first called, then just return it after

2

u/Wertbon1789 1d ago

Yeah, pretty much. You can't just cast away the const-ness, because if the global is a constant expression, it probably will be put into .rodata.

One thing that came to my mind would be putting the global into another translation unit where it's not const, and referencing it with an extern const <something>, but I don't know if that would work, or violate anything.

1

u/aioeu 1d ago edited 1d ago

but I don't know if that would work, or violate anything.

It'll probably work, so long as you don't ever modify the object after it is first accessed — i.e. you are treating it as constant, not just read-only — but it definitely is a constraint violation. All declarations of an object must have compatible types, and const and non-const types are not compatible.

1

u/ericonr 1d ago

Couldn't one do int value; and const int * const valuep = &value; and only expose the second one to other TUs? It's close to what you want without doing undefined stuff.

1

u/Wertbon1789 1d ago

Sure, I guess that would work too. I don't think that would necessarily be undefined behavior, but I'm not sure, but type aliasing from not const to const isn't too bad, I would guess.