Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

c - Const vs Static Const

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...