2

This is my code. I want to test function mbstowcs_s.

#include <stdio.h>
#include <wchar.h>
#include <stdlib.h>
#include <locale.h>
#include <assert.h>


int main()
{
    char MultiByteStr[20] = "a中";
    wchar_t WideByteStr[20];

    printf("%s\n", MultiByteStr);

    char* LocaleInfo = setlocale(LC_CTYPE, "");
    printf("%s\n", LocaleInfo);

    // required length of WideByteStr
    size_t WideStrLen = 0;
    mbstowcs_s(&WideStrLen, NULL, 0, MultiByteStr, 0);
    assert(WideStrLen < 20);
    mbstowcs_s(NULL, WideByteStr, 20, MultiByteStr, WideStrLen);
    WideByteStr[WideStrLen] = L'\0';
    wprintf(L"%ls\n", WideByteStr);

    return 0;
}

I test this code on windows platform successfully, but failed on linux platform. Below is the error message.

test.c: In function ‘main’:
test.c:20:5: warning: implicit declaration of function ‘mbstowcs_s’ [-Wimplicit-function-declaration]
     mbstowcs_s(&WideStrLen, NULL, 0, MultiByteStr, 0);
     ^
/tmp/ccqzP6HF.o: In function `main':
test.c:(.text+0x77): undefined reference to `mbstowcs_s'
test.c:(.text+0xc3): undefined reference to `mbstowcs_s'
collect2: error: ld returned 1 exit status
yintao
  • 23
  • 4
  • It is a [C11 function](http://en.cppreference.com/w/c/string/multibyte/mbstowcs). You probably ought to tell your compiler about it. – Hans Passant Oct 12 '17 at 15:30
  • 1
    This is a `C11` from the optional Annex K, so it might not exist on your platform. If it would, you'd still have to enable Annex K with the appropriate macro before all `#include`. – Jens Gustedt Oct 12 '17 at 15:35
  • 1
    See [Do you use the TR-24731 “safe” functions?](https://stackoverflow.com/q/372980/15168) for more information about the `_s` functions and Unix. – Jonathan Leffler Oct 12 '17 at 15:44
  • The control macro is `__STDC_WANT_LIB_EXT1__`. The result of not defining it at all is implementation-defined, so on some implementations you may not in fact need to define it. With that said, if you use the Annex-K functions then you *should* define it -- to `1` --, before any system headers are directly or indirectly `#include`d. That way, you have the desired semantics on *every* conforming C11 implementation that in fact supports these optional features. Not all do support them, however, so for greatest portability, you should not rely on the system to provide them. – John Bollinger Oct 12 '17 at 15:45
  • The is no `man` page entry on linux for `mbstowcs_s` so you can expect that the function (really a windows/MSDN function) to not be found on linux – user3629249 Oct 12 '17 at 20:28

0 Answers0