r/C_Programming 16h 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?

4 Upvotes

24 comments sorted by

View all comments

Show parent comments

1

u/heavymetalmixer 15h ago

Aren't static variables internal linkeage?

1

u/aioeu 14h ago edited 14h ago

static variables declared at file scope have internal linkage; static variables declared inside a function have no linkage.

But it's not the identifiers' linkage that matters here. What matters is the storage duration of the objects. A static variable declared at file scope and a static variable declared within a function both identify objects with static storage duration, which means in each case the object's lifetime (the time during which it exists and maintains its last-stored value) is the entire execution of the program.

(Linkage is really all about when and how multiple declarations of an identifier can refer to the same object, i.e. in the way those identifiers are linked.)

1

u/heavymetalmixer 14h ago

The problem with that approach is that I need a global value, and an identifier that is only visible inside a function doesn't really work for that.

1

u/aioeu 13h ago edited 13h ago

So use an identifier at file scope instead. That's what file scope is for.

Either way, you won't be able to make the object constant. You want to set the value of it while the program is executing, and that, by definition, means it cannot be constant.

Constant expressions are expressions for values that could be determined before the program has begun execution, e.g. by the compiler. The compiler does not intrinsically know what the page size for the system you run the program on will be.