1

I am wondering why my use of swprintf_s is generating the linker warning warning: implicit declaration of function 'swprintf_s'

I have this headers:

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <windows.h>
#include <tchar.h>

And

LPCWSTR foo = L"É %s";
LPCWSTR arg = "bá";
LPCWSTR msg = malloc(wcslen((wchar_t*)foo) + wcslen((wchar_t*)arg) + 1);
swprintf_s(msg, (wchar_t*)foo, (wchar_t*)arg);

How can I fix this?

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
Jack
  • 16,276
  • 55
  • 159
  • 284
  • 2
    hrm. According to [the docs](http://msdn.microsoft.com/en-us/library/ce3zzk1k%28v=vs.80%29.aspx) you should get it with `stdio.h`. – pb2q Jun 12 '12 at 16:26
  • What version of Visual C++ are you using? – wkl Jun 12 '12 at 16:27
  • 3
    @Jack - `swprintf_s` is a Microsoft addition, it's not included with GCC or `libc`. – wkl Jun 12 '12 at 16:33

1 Answers1

3

All of the _s functions (swprintf_s, memcpy_s) are Microsoft additions. They are part of Microsoft's C library. When you use GCC, you will end up using a different C library, which doesn't include Microsoft's additions (but may include its own additions). Microsoft calls their C library the "CRT" or "C runtime", GCC users refer to it as "libc" or even "glibc" (which is a specific implementation).

If you look at a list of functions in Microsoft's standard C library (MSDN docs), with a sharp eye you'll notice a fairly large number of non-standard functions. Most of these are part of Microsoft's "security enhancements" (MSDN docs). In general, I recommend avoiding the security enhancements since they are non-portable and they are not necessary for writing safe code.

Fix: You can use swprintf instead of swprintf_s. The swprintf function is part of the C standard so it is present on many implementations (although it should be avoided on non-Windows platforms, since it uses wchar_t).

LPCWSTR foo = L"É %s";
LPCWSTR arg = L"bá";
size_t msgbuflen = wcslen(foo) + wcslen(arg) + 1;
LPCWSTR msg = malloc(len);
if (!msg) error...;
swprintf(msg, msgbuflen, foo, arg);

Note that LPCWSTR is just a fancy typedef for const wchar_t *, so you don't need to cast it to wchar_t *.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415