Search code examples
clinuxposixlibcstrerror

How to use strerror_l with current locale?


I'm fixing some Linux code which used strerror (not thread-safe) for multi-threading. I found that strerror_r and strerror_l are both thread-safe. Due to different definitions for strerror_r (depending on _GNU_SOURCE it is differently defined) I'd like to use the newer strerror_l function, but how am I supposed to obtain a locale_t object for the current locale? I'm not using iconv or anything, just plain libc, and I don't see how I can obtain a "default locale" object (I don't care in what language the error is printed, I just want a human readable string.)


Solution

  • If you pass "" to the locale parameter newlocale will allocate a locale object set to the current native locale[1]

    [1]http://pubs.opengroup.org/onlinepubs/9699919799/functions/newlocale.html

    static  locale_t locale;
    
    bool MyStrerrorInit(void)
    {
        locale = newlocale(LC_ALL_MASK,"",(locale_t)0);
        
        if (locale == (locale_t)0) {
           return false;
        }
     
        return true;
    }
        
    char * MyStrerror(int error)
    {
        return strerror_l(error, locale);
    }