Posts Tagged ‘portability’
&errno as thread identifier
By chys on March 13th, 2010
Thread identifiers may have different types in different systems – pthread_t under POSIX; uintptr_t or HANDLE under Windows. They are usually integers or pointers, but POSIX actually allows structures though not usually found. This leads to a little difficulty in portability.
A trick, used by OpenSSL (if not overridden by calling CRYPTO_set_id_callback), is to use &errno as the thread identifier.
Per C standard, errno must be a modifiable lvalue, and thus we can safely take its address – &errno. And under any practically usable thread implementation, errno must be thread-local, which means &errno is different in different threads.
Note: It seems OpenSSL defaults to &errno only since 0.9.8m. Earlier versions always require the user to call CRYPTO_set_id_callback.
Tags: multithread, portability
wprintf(“%s”,…)
By chys on June 28th, 2009Microsoft and GNU interprets %s differently in the wide-string version of the printf-family functions (wprintf, etc.)
Microsoft: “when used with wprintf functions, specifies a wide-character string.”
C99 and GNU: “If no l modifier is present: The const char * argument is expected to be a pointer to an array of character type (pointer to a string).”
Fortunately, both accept “%ls” for wide strings.
Unfortunately, the only supported format specifier for multi-byte (narrow) strings in C99 is “%s”, which Microsoft interpret differently.
Fortunately, the specifier that Microsoft recommends for multi-byte strings, “%hs”, is also accepted by many other C libraries, though undocumented. Such acceptance is very reasonable – the unknown prefix It seems such acceptance is necessary in order to strictly conform to the wording of C99.h is simply ignored. (I tested it with GNU and Solaris C libraries.)
Microsoft wprintf |
GNU wprintf |
C99 | |
%s |
Wide | Narrow | Narrow |
%S |
Narrow | Wide (deprecated) | |
%hs |
Narrow | Narrow (undocumented) | |
%ls |
Wide | Wide | Wide |
To draw a conclusion:
- Everybody agrees that, in
wprintf, “%ls” specifies a wide string. (I’m not sure whether VC6 supports it.) - There is no consensus on the specifier for multi-byte strings. The best practical choice is “%hs”.
This table and conclusion also apply to the “%c” family.
Tags: C/C++, portability
