开发者

g++ creates several symbols of a const?

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 ?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜