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?
Use
1+strlen(POLICY)
and turn on compiler optimizations. GCC will replace strlen(S) with the length of S at compile time if the value from S is known at compile time.Use
sizeof()
. e.g.sizeof("blah")
will evaluate to5
at compile-time (5, not 4, because the string literal always includes an implicit null-termination character).I have a similar problem when using an outdated compiler (VisualDSP) on an embedded platform which does not yet support C++11 (and so I can't use constexpr).
I don't need to evaluate the string length in the precompiler, but I do need to optimize it into a single assignment.
Just in case someone needs this in the future, here's my extremely hacky solution which should work on even crappy compilers as long as they do proper optimization:
This STRLEN macro will give you the length of the string literal that you provide it, as long as it's less than 10 characters long. In my case this is enough, but in the OPs case the macro may need to be extended (a lot). Since it is highly repetitive you could easily write a script to create a macro that accepts 1000 characters.
PS: This is just a simple offshoot of the problem I was really trying to fix, which is a statically-computed HASH value for a string so I don't need to use any strings in my embedded system. In case anyone is interested (it would have saved me a day of searching and solving), this will do a FNV hash on a small string literal that can be optimized away into a single assignment:
sizeof
works at compile timeIf you need a pre-processor symbol with the size, just count the characters and write the symbol yourself :-)