undefined reference to `strcpy_s' can't compile

medis picture medis · May 18, 2013 · Viewed 7.1k times · Source

i follow the book and can't compile this example. Any suggestions?

  1 #define __STDC_WANT_LIB_EXT1__ 1
  2 #include <string.h>
  3 #include <stdio.h>
  4 
  5 
  6 int main(void)
  7 {
  8         char source[] = "Here we go...";
  9         char destination[50];
 10 
 11         if(strcpy_s(destination, sizeof(destination), source))
 12                 printf("An error occurred copying the string.n");
 13 
 14 
 15         return 0;
 16 }

error:

/tmp/ccc5KZDZ.o: In function `main':
test.c:(.text+0x48): undefined reference to `strcpy_s'
collect2: error: ld returned 1 exit status

Answer

Jonathan Leffler picture Jonathan Leffler · May 18, 2013

The strcpy_s() function is defined in TR 24731-1 (see Do you use the TR 24731 'safe' functions), and also in optional Annex K of ISO/IEC 9899:2011 (the C 2011 standard).

You can test whether your implementation supports it with:

__STDC_LIB_EXT1__ The integer constant 200509L, intended to indicate conformance to this Technical Report.

(according to the TR). Annex K simply says:

An implementation that defines __STDC_LIB_EXT1__ shall conform to the specifications in this annex.380)

380) Implementations that do not define __STDC_LIB_EXT1__ are not required to conform to these specifications.

This answer indicates that the TC1 (Technical Corrigenda 1) for the C 2011 standard defines that __STDC_LIB_EXT1__ should be 201112L (Dec 2011) for the Annex K version of the functions. I've not tracked whether there are differences between Annex K and TR 24731-1.

So, you should be able to test whether your library supports strcpy_s() by testing __STDC_LIB_EXT1__, but it is optional. There was apparently a statement by Ulrich Drepper that the GNU C Library would not support the TR 24731-1 functions; I don't know whether that still holds.

Also, be aware that the Microsoft interfaces to some of these functions is different from the standard interfaces to the same function (vsnprintf_s(), for example). That limits their usefulness as a cross-platform portability tool.