Const vs Static Const

It depends on your system, and on how you use the variable. For static variables:

Case 1: You never use the variable, and the compiler silently discards it. This cannot happen with extern variables.

Case 2: You use the variable, but you never take its address. The compiler converts use of the variable to immediate operands, just as if it were a #define or enum. The compiler can still convert extern static to immediate operands, but it must still find an address for it anyway.

Case 3: You use the variable and take its address, the compiler is forced to find a place to put it in the object code, exactly as if it were extern.

As for “data” versus “program” memory, well, that is very specific to the system you are using. On my Linux x64/ELF system, it will probably get put in the .rodata section, which goes in the same segment as code (.text), but a different segment from read-write data sections (.bss, .data). My system appears not to create a separate segment for read-only non-executable data.

Addendum: Note that the behavior is different in C++. In C++, a const variable has internal linkage by default, so static const is redundant and extern const is necessary to get a constant with external linkage.

Leave a Comment