r/C_Programming • • Sep 11 '26

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?

6 Upvotes

40 comments sorted by

View all comments

Show parent comment

1

u/WittyStick Sep 12 '26 edited Sep 12 '26

They do, which is why I've suggested to not even expose set_page_size in the header - but we still need to somehow call it, which is where the constructor function trick is useful (awful to use on MSVC, but doable).

Destructor functions are even more awkward if we need to clean up any resource used by the constructors. With GCC and Clang it's just __attribute__((destructor)), which is simple.

There's no direct equivalent in MSVC, but we can utilize atexit() to cause another function to execute after main.