tags:

views:

108

answers:

3

In one of my header (C++) files I changed

   #define TIMEOUT 10

to the more(?) C++ way:

const int TIMEOUT = 10;

It seems however, g++(v 4.4.3) now includes this symbol several times in the binary.

$ nm -C build/ipd/ipd |head
08050420 T ToUnixTime
08050470 T ParseTime
080504c0 T ParseISOTime
080518e4 r TIMEOUT
080518ec r TIMEOUT
080518f4 r TIMEOUT
080518fc r TIMEOUT
080503e0 T HandleMessage

How come ?

+7  A: 

You have probably included your header in four separate translation units (.cpp files).

Namespace-scope const variables not declared extern are implicitly static, so there will be one for each translation unit in which the header is included.

James McNellis
So, should I rather just keep the #define ?
nissen
@nissen: If you really want exactly one copy, declare it `extern` in the header and then define it in exactly one cpp file, or for integer constants use the enumeration trick that Potatoswatter shows in his answer.
James McNellis
+3  A: 

Try an enum instead. It's much like a #define, you can't take a reference to it, and it's guaranteed not to take any space anywhere.

enum { TIMEOUT = 10 };

But if it's not causing you any trouble, I wouldn't worry about it one way or another. The const int way is just fine and we're talking about 16 bytes, give or take.

Potatoswatter
A: 

The compiler may have found that copying the symbol is more efficient than referencing it. This is due to the const modifier.

In many instances, loading a register with an "immediate" value (one stored in the executable) is more efficient than loading from a location in ROM (Read Only Memory), which uses indirect addressing.

I would not worry about duplications of a constant integer in many object files, unless it makes the files too large to fit on the hard drive. Also, object files are a interim storage for data until the executable or libraries are generated.

I suggest concentrating more on the quality and robustness of your application than the internals of object files.

Thomas Matthews