2017-10-28 205 views
0

編輯問題是:「‘strnlen’的功能隱式聲明」:我怎麼刪除警告/EDIT 編譯(特殊切下的測試只有一個的#include)gcc的警告當方言C99或C11使用

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

由於沒有方言,它編譯沒有任何警告的

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 

使方言C99在警告

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 

使方言C11(我的首選)在警告

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 

額外的信息:

  • 項目

    Oher部分失敗下C90編譯,所以沒有信息可以

  • 在Ubuntu 16.04下運行,這是14.04的升級

  • 使用

    Eclipse IDE中的C/C++開發人員

    版本:Neon.3版本(4.6.3) 版本ID:20170314-1500

  • 人strnlen

給出

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 
+3

你的問題是什麼?您向編譯器要求c99或c11合規性,並且這兩個版本都沒有在string.h頭文件中提供'strnlen()'函數。 – nos

+2

使用gnu99,而不是c99。作爲替代,手冊頁告訴你定義_XOPEN_SOURCE ... –

+0

@nos在其他地方在stackoverflow中搜索導致我明白strnlen在string.h中,就像strncpy – brewmanz

回答

0

在Linux和MacOS等POSIX系統上,您需要通過將-D_POSIX_C_SOURCE=200809L傳遞給編譯器或在#include之前編寫#define _POSIX_C_SOURCE 200809L來定義它指定爲特徵測試宏的宏。

在Windows上,您不需要任何特殊的宏,可以直接使用strnlen

請注意,C標準實際上並沒有定義strnlen,而是strnlen_s,它相似但不完全相同。然而,很多實現並沒有包含它,甚至對於那些你可能需要在包括string.h之前將__STDC_WANT_LIB_EXT1__定義爲1的實現。

+0

'strnlen_s'只是C11邊界檢查界面的一部分,這是一個可選功能,它似乎沒有太多的編譯器支持方式(?)。 – Lundin

+0

@Lundin Huh,你說得對。由於共同構成絕大多數實現的Windows和POSIX都具有'strnlen',所以即使它不是標準化的,它在實踐中也更具可移植性。 –

+0

@Lundin我不假設你知道爲什麼C標準委員會在大量實現已經擁有'strnlen'的時候用'strnlen_s'去了,它實際上並沒有給你帶來額外的安全(因爲你可以檢查'NULL'你自己)? –