Search code examples
cmacrosc-preprocessorc-stringsstrlen

Determine #defined string length at compile time


I have a C-program (an Apache module, i.e. the program runs often), which is going to write() a 0-terminated string over a socket, so I need to know its length.

The string is #defined as:

#define POLICY "<?xml version=\"1.0\"?>\n" \
   "<!DOCTYPE cross-domain-policy SYSTEM\n" \
   "\"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">\n" \
   "<cross-domain-policy>\n" \
   "<allow-access-from domain=\"*\" to-ports=\"8080\"/>\n" \
   "</cross-domain-policy>\0"

Is there please a way, better than using strlen(POLICY)+1 at the runtime (and thus calculating the length again and again)?

A preprocessor directive, which would allow setting POLICY_LENGTH already at compile time?


Solution

  • Use sizeof(). e.g. sizeof("blah") will evaluate to 5 at compile-time (5, not 4, because the string literal always includes an implicit null-termination character).