Reputation: 41
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 ?
Upvotes: 4
Views: 165
Reputation: 57678
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.
Upvotes: 0
Reputation: 137800
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.
Upvotes: 3
Reputation: 355049
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.
Upvotes: 6