Does G ++ create multiple const characters?

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

#define TIMEOUT 10 

to more (?) C ++ method:

 const int TIMEOUT = 10; 

However, it seems g ++ (v 4.4.3) now includes this character several times in binary format.

 $ 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 did it happen?

+4
source share
3 answers

You may have included your title in four separate translation units (.cpp files).

Namespace constant variables not declared extern are implicitly static , so there will be one for each translation unit that includes the header.

+6
source

Try enum instead. This is very similar to #define , you cannot reference it, and it is guaranteed to leave no place anywhere.

 enum { TIMEOUT = 10 }; 

But if this does not cause you any problems, I would somehow not be worried about it. The const int path is very good, and we are talking about 16 bytes, give or accept.

+3
source

Perhaps the compiler found that copying a character is more efficient than referencing it. This is due to the const modifier.

In many cases, loading a register with an β€œimmediate” value (one of which is stored in an executable file) is more efficient than loading from a location in ROM (read-only memory) that uses indirect addressing.

I would not worry about duplicating a constant integer in many object files, unless it makes the files too large to fit on the hard drive. In addition, object files are an intermediate data store until an executable file or libraries are created.

I suggest focusing more on the quality and reliability of your application than on internal object files.

0
source

Source: https://habr.com/ru/post/1307735/


All Articles