2017-10-28 104 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'你自己)? –