ARM Technical Support Knowledge Articles

MERGING DUPLICATE CONSTANT STRINGS

Applies to: General Topics

Answer


Information in this article applies to:


QUESTION

How can I get the compiler to merge duplicate strings in my program?

ANSWER

The Keil C compilers already do this. For example, the following code:

#include <stdio.h>

void main (void)
{
printf ("This is a test
");
printf ("This is a test
");
printf ("This is a test
");
printf ("This is a test
");
printf ("This is a test
");
}

Generates the following assembly listing:

             ; FUNCTION main (BEGIN)
                                           ; SOURCE LINE # 5
0000 7BFF              MOV     R3,#0FFH
0002 7A00        R     MOV     R2,#HIGH ?SC_0
0004 7900        R     MOV     R1,#LOW ?SC_0
0006 120000      E     LCALL   _printf
                                           ; SOURCE LINE # 6
0009 7BFF              MOV     R3,#0FFH
000B 7A00        R     MOV     R2,#HIGH ?SC_0
000D 7900        R     MOV     R1,#LOW ?SC_0
000F 120000      E     LCALL   _printf
                                           ; SOURCE LINE # 7
0012 7BFF              MOV     R3,#0FFH
0014 7A00        R     MOV     R2,#HIGH ?SC_0
0016 7900        R     MOV     R1,#LOW ?SC_0
0018 120000      E     LCALL   _printf
                                           ; SOURCE LINE # 8
001B 7BFF              MOV     R3,#0FFH
001D 7A00        R     MOV     R2,#HIGH ?SC_0
001F 7900        R     MOV     R1,#LOW ?SC_0
0021 120000      E     LCALL   _printf
                                           ; SOURCE LINE # 9
0024 7BFF              MOV     R3,#0FFH
0026 7A00        R     MOV     R2,#HIGH ?SC_0
0028 7900        R     MOV     R1,#LOW ?SC_0
002A 020000      E     LJMP    _printf
             ; FUNCTION main (END)

As you can see, the string constant at ?SC_0 is accessed for each call to printf. And, in the module information:

MODULE INFORMATION:   STATIC OVERLAYABLE
   CODE SIZE        =     45    ----
   CONSTANT SIZE    =     16    ----
   XDATA SIZE       =   ----    ----
   PDATA SIZE       =   ----    ----
   DATA SIZE        =   ----    ----
   IDATA SIZE       =   ----    ----
   BIT SIZE         =   ----    ----
END OF MODULE INFORMATION.

only 16 bytes of memory are used for the constant space (the string, "This is a test ").

As an alternative, you may specifically declare constant strings that you will use in multiple places as follows:

#include <stdio.h>

const char code strThisIsATest [] = "This is a test
";

void main (void)
{
printf (strThisIsATest);
printf (strThisIsATest);
printf (strThisIsATest);
printf (strThisIsATest);
printf (strThisIsATest);
}

Article last edited on: 2001-03-26 00:00:00

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential