Last Updated: February 25, 2016
·
10.02K
· namuol

Compile-Time String Concatenation in C

In C99-compliant compilers, adjacent strings are concatenated at compile-time.

int main()
{
  printf("Hello, " /* Cruel */ "World!\n");
}

This allows you to programmatically build strings at compile-time by utilizing pre-processor macros:

#define PKG "com/example"
#define CLASSNAME(pkg, cls) pkg "/" cls
// ...
char* classNames[] = {
    CLASSNAME(PKG, "Foo"), // --> "com/example/Foo"
    CLASSNAME(PKG, "Bar"), // --> "com/example/Bar"
    CLASSNAME(PKG, "Baz"), // --> "com/example/Baz"
    CLASSNAME(PKG, "Wiz"), // --> "com/example/Wiz"
    CLASSNAME(PKG, "Wat")  // --> "com/example/Wat"
};