July 2, 2008

Data & Read-only sections

Filed under: Lowlevel — by suasol @ 9:30 am

First lets look at the code generated with some simple examples.

extern int global_writable_var = 9; // a.cpp
extern const int global_const_var = 9; // a.cpp

Generate the assembly source with

cl /c /Fa a.cpp # MSVC: /c means compile only, don't link. /Fa means output assembly
gcc -c -S a.cpp # GCC: -c means compile only, don't link. -S means output assembly

And we get:

// MSVC : a.asm
PUBLIC	?global_writable_var@@3HA	; global_writable_var
PUBLIC	?global_const_var@@3HB		; global_const_var
?global_const_var@@3HB DD 09H		; global_const_var
?global_writable_var@@3HA DD 09H		; global_writable_var

// GCC : a.s
.globl global_writable_var                  ; attributes of the variable
        .align 4
        .type   global_writable_var, @object
        .size   global_writable_var, 4
        .long   9                           ; variable definition
.globl global_const_var
        .section        .rodata
        .align 4
        .type   global_const_var, @object
        .size   global_const_var, 4
        .long   9

The key thing to notice here is that the compiler puts constant data into a separate areas (try adding more variables). Typically these areas (known as the _data and _const segments on windows, known as .data and .rodata sections on unix) will have different memory protection bits enabled – thus writes to global_const_var would cause a hardware exception. Also if you’re compiling a shared library or have several executables running, then each time the library is loaded the data segment is duplicated, but the constant section may be shared between all instances.

Thus if you have a library (dll) which is linked many times (as is very common in linux for instance – try “ldd /path/to/executable” on some programs), the overhead can really add up.

See also:


1 Comment »

  1. […] Filed under: Uncategorized — by suasol @ 10:47 am (You may want to have a look at the previous article for a refresher on data and const data […]

    Pingback by GNU C++ POD madness « Blig — July 2, 2008 @ 10:47 am |Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: