[webkit-dev] static const
Albert J. Wong (王重傑)
ajwong at chromium.org
Wed Sep 2 11:29:47 PDT 2009
On Wed, Sep 2, 2009 at 10:13 AM, Peter Kasting <pkasting at google.com> wrote:
> On Wed, Sep 2, 2009 at 9:55 AM, Alexey Proskuryakov <ap at webkit.org> wrote:
>
>> I don't have a normative reference at hand, but I'm fairly sure that both
>> give internal linkage in C++ (unlike in C).
>>
>>
>> http://stackoverflow.com/questions/998425/why-does-const-imply-internal-linkage-in-c-when-it-doesnt-in-c
>> http://bytes.com/topic/c/answers/62013-const-has-internal-linkage-c
>
>
> Interesting; I hadn't heard this before.
>
> It has been a number of years since I read the relevant specs. My
> probably-faulty memory recalls things about most C compilers having a
> concept of "common" linkage, where "int a;" defined in both foo.c and bar.c
> would be accepted by the linker and turned into a single symbol. Whether
> this was the default varied, but apparently a lot of older C code depended
> on it...
>
> I had also thought that C++ aimed to have all file-scope objects (not just
> const ones) have internal linkage unless declared "extern", but I had
> thought that wasn't actually the case.
>
> So apparently the only part I'm confident on is that Stroustrup deprecated
> "static" for internal linkage and recommends anonymous namespaces in the
> general case :)
>
[ apologies in advance if this accidentally double sends ]
I think there is also a slight difference between "const" versus "static
const" in a function scope. Assuming it doesn't get constant propagated
(eg., if you take the address of it), then one ends up on the stack with an
added initialization per call, and the other not. Here's a simple code
snippet and an assembly dump:
>
void print_ptr(const int* f) {
> printf("%d\n", *f);
> }
>
int static_const_ptr() {
> static const int g = 3;
> print_ptr(&g);
> }
>
int just_const_ptr() {
> const int x = 3;
> print_ptr(&x);
> }
>
static_const_ptr():
> push %ebp
> mov %esp,%ebp
> sub $0x8,%esp
> movl $0x0,(%esp)
> call 10e <static_const_ptr()+0xe>
> leave
> ret
>
just_const_ptr():
> push %ebp
> mov %esp,%ebp
> sub $0x18,%esp
> lea -0x4(%ebp),%eax
> mov %eax,(%esp)
> movl $0x3,-0x4(%ebp)
> call f4 <just_const_ptr()+0x14>
> leave
> ret
> lea 0x0(%esi),%esi
>
This was compiled on a linux box with "g++ -O2 -m32 -c", and dumped with
"objdump -DCs".
>
With -O2, if print_ptr is changed to take a reference, there is no
difference between the two functions. With -O0, pass by reference retains
this dichotomy.
>
Doesn't probably matter in most cases, but usually I end up using "static
const" just to be safe.
>
-Albert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20090902/ab5ee781/attachment.html>
More information about the webkit-dev
mailing list