1

the command "what" is used on my project to query some peaces of informations about executables (compilation date, version, ...). I am fixing a bug where one line is missing in what output since we have changed the version of gcc. The string was defined in a local scope:

char string_for_what = "@(#) Component comp1";

This string was never used. I assume the optimizer has removed it.

I think the normal correction should be to declare the string at a global scope. But what prohibits a future compiler to optimize it away if it is not used ?

I have thought about calling strlen("@(#) Component comp1") to ensure that the string is used, but it seems that clang is optimizing away this call on constant strings.

Shoud I call fopen("@(#) Component comp1") ? If someone creates a file with this name, I may lose one file descriptor. This seems to work but it seems also a bit overkill.

BOC
  • 1,109
  • 10
  • 20
  • Possible duplicate of http://stackoverflow.com/questions/16349557/does-gcc-have-any-options-to-add-version-info-in-elf-binary-file – Alan Stokes Apr 23 '16 at 21:58

1 Answers1

1

Moving this declaration to a global scope may easily lead to violation of One Definition Rule.

You can prohibit optimizing out these variables using volatile keyword.

[C++11: 3.7.3:] If a variable with automatic storage duration has initialization or a destructor with side effects, it shall not be destroyed before the end of its block, nor shall it be eliminated as an optimization even if it appears to be unused, (...)

and:

[C++11: 1.9.12:] Accessing an object designated by a volatile glvalue (3.10), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects

Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79