Microsoft KB Archive/87634

= PRB: Constant String Is Eliminated by the C++ Compiler =

Article ID: 87634

Article Last Modified on 12/11/2003

-

APPLIES TO


 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 1.5 Professional Edition
 * Microsoft Visual C++ 1.51
 * Microsoft Visual C++ 1.52 Professional Edition
 * Microsoft Visual C++ 1.0 Professional Edition
 * Microsoft Visual C++ 2.0 Professional Edition
 * Microsoft Visual C++ 2.1
 * Microsoft Visual C++ 4.0 Standard Edition
 * Microsoft Visual C++ 4.1 Subscription
 * Microsoft Visual C++ 4.2 Professional Edition
 * Microsoft Visual C++ 5.0 Standard Edition
 * Microsoft Visual C++ 6.0 Service Pack 5

-



This article was previously published under Q87634



SYMPTOMS
The Microsoft C/C++ versions 7.0 and later compilers eliminate unreferenced constant strings. This happens only with C++ source, not C source. The string is declared in the source file, but is not included in the resulting object module.



CAUSE
In C++, const variables have internal linkage. This is different from the way that C handles const variables.

In this case, because the C++ compiler can process only one source file at a time, the string is eliminated if it is not referenced in the file in which it is declared, even if it is referenced from another file.



RESOLUTION
The solution is to declare the const string as &quot;extern&quot;. This provides external linkage, telling the compiler that the string may be used in another module, and not to assume that it is an unreferenced symbol; for example   const char sz[] = &quot;\&quot;the string\&quot;&quot;; would be optimized away in a C++ module, but the following string would not:   extern const char sz[] = &quot;\&quot;the string&quot;\&quot;;



MORE INFORMATION
While this behavior is not a bug in the compiler, the effects of this optimization may cause unexpected results. If a string is declared and initialized in one module, and referenced only in another module, the string will be eliminated from the first module. This means that the other file will not have access to the information used in the initialization of the string.

For more information on internal and external linkage, see section 2.4 of the &quot;&quot;C++ Language Reference&quot;&quot; supplied with C/C++ version 7.0 and Visual C++, or refer to the online help supplied with Visual C++.

Additional query words: 8.00 8.00c 9.00 9.10 L2029

Keywords: kbprb kbcpponly kbcompiler KB87634

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.