Keil Logo

GENERAL: STRING TABLES IN C


Information in this article applies to:

  • C166 Version 3.12
  • C166 Version 4.01
  • C251 Version 2.14
  • C51 Version 5.50

QUESTION

I have an application that I have to port to various foreign languages. I would like to create a string table and then change the strings for each language that I will support. What's the best way to encapsulate my strings in a single file and access them from my C program?

ANSWER

There are a number of good ways to do this. The following suggestion is only one of them. However, it is relatively easy to implement and understand. It uses 3 concepts that you must introduce into your program.

  1. Use an array of pointers to the message strings.
  2. Use a list of manifest constants to index into the pointer array.
  3. Use a single macro to access any string.

The first step is to create an assembly file (a very simple one) that contains the messages and a table of pointers to the messages. Since you will probably want to locate the table at a fixed address, this is best way to do that. For example:

;The following is an array of pointers to the messages

cseg      at    08000  ; *** Change this for your assembler ***

hstrtab:  dw    str1
          dw    str2
          dw    str3
          dw    str4

; Here are the messages
str1:     db    'Bon Jour', 0
str2:     db    'Adios', 0
str3:     db    'Merci', 0
str4:     db    'Please', 0

end

Next, create a manifest constant (using #define or enum) for each message in the table. You will use these to index into the array. For example:

enum message_strings
  {
  MSG_HELLO = 0,
  MSG_GOODBYE,
  MSG_THANKS,
  MSG_PLEASE
  };

Finally, you need a macro that lets you reference strtab in your C program:

#define MSGTAB ((char code * code *) 0x8000)

The only trick here is that the addresses (0x8000 in the C program and 8000h in the assembly file) must match.

Now, you are ready to access the strings in your C program.

void main (void)
{
SCON  = 0x50;   /* SCON: mode 1, 8-bit UART, enable rcvr */
TMOD |= 0x20;   /* TMOD: timer 1, mode 2, 8-bit reload */
TH1   = 221;    /* TH1:  reload value for 1200 baud @ 16MHz */
TR1   = 1;      /* TR1:  timer 1 run */
TI    = 1;      /* TI:   set TI to send first char of UART */

printf ("%s\n", MSGTAB [MSG_HELLO]);
printf ("%s\n", MSGTAB [MSG_GOODBYE]);
printf ("%s\n", MSGTAB [MSG_THANKS]);
printf ("%s\n", MSGTAB [MSG_PLEASE]);
}

Last Reviewed: Saturday, July 9, 2005


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.