Defining composite static character strings

0

In my job I end up writing code that contains static const character strings, usually sql queries and/or absolute file names, etc. In the latest piece of code I'm writing, I have two strings that are made up of a shared string (a date). Something like this:

#include <iostream>

using std::cout;
using std::endl;

#define SPONGE "Sponge"
static const char SomeString[] = SPONGE "bob Squarepants!";
static const char SomeOtherString[] = "A dirty " SPONGE;

int main() {
   cout << SomeString << endl;
   return 0;
}

Is there a way I can achieve the same result without using a define statement? I want to have the common string defined in one location, so that if I change it in a later date, all strings will be compiled using the updated value.

Notice, both strings are in the read-only segment of the executable:

 elfdump ./a.out  | grep Some
      [47]  0x00010d00 0x00000017  OBJT LOCL  D    0 .rodata        SomeString
      [49]  0x00010d1c 0x0000000f  OBJT LOCL  D    0 .rodata        SomeOtherString

This is something I would like to preserve.

c++
string
asked on Stack Overflow May 12, 2015 by Mustafa Ozturk • edited May 12, 2015 by Mustafa Ozturk

1 Answer

1

You don't need macros to concatenate two strings. Simply write two string literals one after the other. Something like:

"Sponge" "bob Squarepants!";

Is the same. However if you want to concatenate the values of two string literals, you will have to use strcat.


User contributions licensed under CC BY-SA 3.0