0

I have a VisualStudio C++ project with a Test.c file and it is marked as 'Compile as C++ Code (/TP)'.

The Test.c contains only the below variable, const int test123 = 100;

After compilation, I could not find this variable in Test.obj file. I have used 'dumpbin /symbols' command to export the obj file. What could be the reason for this variable not available in obj file?

  • objfile contains only below items
File Type: COFF OBJECT

COFF SYMBOL TABLE
000 010575C2 ABS    notype       Static       | @comp.id
001 80010390 ABS    notype       Static       | @feat.00
002 00000002 ABS    notype       Static       | @vol.md
003 00000000 SECT1  notype       Static       | .drectve
    Section length   41, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000
006 00000000 SECT2  notype       Static       | .debug$S
    Section length   F8, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000
009 00000000 SECT3  notype       Static       | .debug$T
    Section length   78, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000
00C 00000000 SECT4  notype       Static       | .chks64
    Section length   20, #relocs    0, #linenums    0, checksum        0
    Relocation CRC 00000000

String Table Size = 0x0 bytes

  Summary

          20 .chks64
          F8 .debug$S
          78 .debug$T
          41 .drectve

The variable is available in obj after removing the 'const'.

vvv444
  • 2,764
  • 1
  • 14
  • 25
  • 4
    The compiler is allowed to optimize out variables it doesn't need. – ChrisMM May 25 '23 at 16:25
  • 2
    Global `const` implies static linkage. – 273K May 25 '23 at 16:28
  • Optimization is disabled in settings – muthtvm1 ss May 25 '23 at 16:29
  • 3
    The compiler may have decided to place the constants in the code section, right where they are used. No need to propagate the variable name, since it's just a number. – Thomas Matthews May 25 '23 at 16:29
  • 2
    Does this answer your question? [Why does const imply internal linkage in C++, when it doesn't in C?](https://stackoverflow.com/questions/998425/why-does-const-imply-internal-linkage-in-c-when-it-doesnt-in-c) – vvv444 May 25 '23 at 17:06
  • As a compiler you don't have to store the value in memory, but can just use 100 whenever needed. Don't need an optimizer to see that! – BoP May 25 '23 at 20:36
  • Did the answer below solve your problem? [What is external linkage and internal linkage?](https://stackoverflow.com/questions/1358400/what-is-external-linkage-and-internal-linkage) – Minxin Yu - MSFT Jun 01 '23 at 09:47

1 Answers1

4

Global const variables in C++ have static linkage and that explains why you don't see it as a symbol in the object file.

https://learn.microsoft.com/en-us/cpp/error-messages/tool-errors/global-constants-in-cpp?view=msvc-170

Also, this is well explained in this answer.

vvv444
  • 2,764
  • 1
  • 14
  • 25