C program not seeing snprintf after including stdio

Viewed 467

I have file command.c:

#include <stdlib.h>
#include <stdio.h> 

#define MAXLEN 1000

/* write_message: if argument != NULL, write argument to group, else open group in vim
 * returns 0 on success
 * returns -1 on failure
 */
int write_message(char *message, char *path, char *group) {
    char *editor, sys_call[MAXLEN];

    editor = "vim";

    if (message == NULL) {
        snprintf(sys_call, MAXLEN, "%s %s%s.txt", editor, path, group);
        printf("sys_call = %s\n", sys_call);
        /*        return system(sys_call);*/
    }

    return 0;
}

when I compile with gcc -Wall -Werror -std=c89 -c command.c I get the error message:

command.c: In function ‘write_message’:
command.c:16:9: error: implicit declaration of function ‘snprintf’ [-Werror=implicit-function-declaration]
   16 |         snprintf(sys_call, MAXLEN, "%s %s%s.txt", editor, path, group);
      |         ^~~~~~~~
command.c:2:1: note: ‘snprintf’ is defined in header ‘<stdio.h>’; did you forget to ‘#include <stdio.h>’?
    1 | #include <stdlib.h>
  +++ |+#include <stdio.h>
cc1: all warnings being treated as errors

I can not use snprintf because it is not defined even though I have included stdio.

1 Answers

The snprintf function is not defined by the the C89 standard, it was only introduced later by C99. Since you are explicitly compiling with -std=c89, GCC will not provide you with such function.

You have different options:

  1. Compile with (at least) -std=c99.
  2. Use the appropriate feature test macros documented in man 3 snprintf, for example adding #define _XOPEN_SOURCE 500 at the very beginning of your .c file (before any #include).
  3. Create your own snprintf() function.
  4. Declare snprintf with the appropriate signature (as shown in man 3 snprintf) and use it anyway since GCC will automatically dynamically link glibc, then pray that the function will be available at runtime. Ok, seriously, do not do this for any reason other than having fun.

PS: you can find a list of new features introduced in C99 on Wikipedia. Among those:

  • new library functions, such as snprintf
Related