How does the compiler (e.g. GCC) allocates const and static const variable, as in, where would it reside? In data memory or program memory?
How does the compiler (e.g. GCC) allocates const and static const variable, as in,
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends on your system, and on how you use the variable. For
staticvariables:Case 1: You never use the variable, and the compiler silently discards it. This cannot happen with
externvariables.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
#defineorenum. The compiler can still convertexternstatic 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
.rodatasection, 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
constvariable has internal linkage by default, sostatic constis redundant andextern constis necessary to get a constant with external linkage.