Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

extern const int; storage operation? vs extern const int size = 100;

16 views
Skip to first unread message

Veek M

unread,
Jan 8, 2017, 6:57:52 AM1/8/17
to
I'm reading C++ and he says that

const int size = 100;

is a symbol table entry and the compiler will do constant folding rather
than allocate by default.

He then goes on to say:
'When you use extern with const however you, force storage to be
allocated' 'Storage must be allocated because extern says "use external
linkage", which means that several translational units must be able to
refer to the item, which requires it to have storage'

therefore,
extern const int size = 100;

will force storage (obvious) however I was wondering if he meant that
the declaration:
extern const int size;

would also force storage? As in, does the compiler go ahead and allocate
storage twice and then optimize it out later during link time?

Alf P. Steinbach

unread,
Jan 8, 2017, 8:52:59 AM1/8/17
to
On 08.01.2017 12:57, Veek M wrote:
> I'm reading C++ and he says that
>
> const int size = 100;
>
> is a symbol table entry and the compiler will do constant folding rather
> than allocate by default.

That depends.

If you take its address, and passing it by reference counts, then it
needs to have storage.


> He then goes on to say:
> 'When you use extern with const however you, force storage to be
> allocated' 'Storage must be allocated because extern says "use external
> linkage", which means that several translational units must be able to
> refer to the item, which requires it to have storage'
>
> therefore,
> extern const int size = 100;
>
> will force storage (obvious) however I was wondering if he meant that
> the declaration:
> extern const int size;
>
> would also force storage? As in, does the compiler go ahead and allocate
> storage twice and then optimize it out later during link time?

Storage is allocated for it (only) in the translation unit where it's
defined.

It's a different matter with `static` member variables of a template
class, and with C++17 `inline` variables.

There, discardable linker records, or something with that functionality,
is necessarily used.


Cheers & hth.,

- Alf

Veek M

unread,
Jan 8, 2017, 10:03:37 AM1/8/17
to
Thanks Alf - reading http://www.lurklurk.org/linkers/linkers.html
will post if i run into something.
0 new messages