brewmanz
brewmanz

Reputation: 1221

gcc warning "implicit declaration of function ‘strnlen’" when dialect c99 or c11 used

EDIT Question is: how do I remove the warning /EDIT compiling (special cut-down test with just one #include)

#include <string.h>
void DeleteMe(){
    const char* pC = "ABC";
    int nLen = strnlen(pC, 255);
    char buffer[256];
    strncpy(buffer, pC, nLen);
}

With no dialect, it compiles no warning as

Building file: ../EzyThread.c
Invoking: GCC C Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"EzyThread.d" -MT"EzyThread.o" -o "EzyThread.o" "../EzyThread.c"
Finished building: ../EzyThread.c

making dialect c99 gives warning

Building file: ../EzyThread.c
Invoking: GCC C Compiler
gcc -std=c99 -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"EzyThread.d" -MT"EzyThread.o" -o "EzyThread.o" "../EzyThread.c"
../EzyThread.c: In function ‘DeleteMe’:
../EzyThread.c:4:13: warning: implicit declaration of function ‘strnlen’ [-Wimplicit-function-declaration]
  int nLen = strnlen(pC, 255);
             ^
Finished building: ../EzyThread.c

making dialect c11 (my preferred option) gives warning

Building file: ../EzyThread.c
Invoking: GCC C Compiler
gcc -std=c11 -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"EzyThread.d" -MT"EzyThread.o" -o "EzyThread.o" "../EzyThread.c"
../EzyThread.c: In function ‘DeleteMe’:
../EzyThread.c:4:13: warning: implicit declaration of function ‘strnlen’ [-Wimplicit-function-declaration]
  int nLen = strnlen(pC, 255);
             ^
Finished building: ../EzyThread.c

Extra info:

gives

STRNLEN(3)                 Linux Programmer's Manual                STRNLEN(3)

NAME
       strnlen - determine the length of a fixed-size string

SYNOPSIS
       #include <string.h>

       size_t strnlen(const char *s, size_t maxlen);

   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

       strnlen():
           Since glibc 2.10:
               _XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
           Before glibc 2.10:
               _GNU_SOURCE

Upvotes: 2

Views: 7076

Answers (2)

Alok
Alok

Reputation: 137

You can use _GNU_SOURCE or _POSIX_C_SOURCE
You can refer to this manual page https://www.man7.org/linux/man-pages/man3/strnlen.3.html

#define _GNU_SOURCE

or

#define _POSIX_C_SOUCRE 200809L

Upvotes: 0

Daniel H
Daniel H

Reputation: 7453

On POSIX systems like Linux and macOS, you need define the macro it specifies as the feature test macro, by passing -D_POSIX_C_SOURCE=200809L to the compiler or writing #define _POSIX_C_SOURCE 200809L before the #include.

On Windows, you don’t need any special macros and can just use strnlen directly.

Note that the C standard doesn't actually define strnlen, but instead strnlen_s, which is similar but not quite identical. However, a lot of implementations don’t include it, and even for those which do you might need to define __STDC_WANT_LIB_EXT1__ to 1 before including string.h.

Upvotes: 2

Related Questions