简体   繁体   English

g ++创建const的几个符号?

[英]g++ creates several symbols of a const?

In one of my header (C++) files I changed 在我的一个标题(C ++)文件中,我改变了

   #define TIMEOUT 10

to the more(?) C++ way: 更多(?)C ++方式:

const int TIMEOUT = 10;

It seems however, g++(v 4.4.3) now includes this symbol several times in the binary. 然而,似乎g ++(v 4.4.3)现在在二进制文件中多次包含此符号。

$ 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). 您可能已将标题包含在四个单独的翻译单元(.cpp文件)中。

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. 未声明为extern命名空间范围const变量是隐式static ,因此每个包含标头的转换单元都有一个。

Try an enum instead. 尝试使用enum It's much like a #define , you can't take a reference to it, and it's guaranteed not to take any space anywhere. 它很像#define ,你不能参考它,它保证不占用任何空间。

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. const int方式很好,我们正在谈论16个字节,给予或采取。

The compiler may have found that copying the symbol is more efficient than referencing it. 编译器可能已经发现复制符号比引用符号更有效。 This is due to the const modifier. 这是由于const修饰符。

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. 在许多情况下,加载具有“立即”值的寄存器(存储在可执行文件中的值)比从使用间接寻址的ROM(只读存储器)中的位置加载更有效。

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. 我建议更多地关注应用程序的质量和健壮性,而不是目标文件的内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM