今天編譯公司源代碼的時候,發現memmem函數一直報出警告信息warning: implicit declaration of function 'memmem',即使加了string.h頭文件也依然報警告。於是查找string.h頭文件中memmem聲明,
發現了#ifdef __USE_GNU,再查找string.h頭文件中包含的#include <features.h>,發現需要開啟_GUN_SOURCE才能打開__USE_GNU。在源碼中加上一條#define _GNU_SOURCE后,編譯果然可以通過。
在網上查找關於宏_GUN_SOURCE的有關資料,也發現同樣開發者遇到過類似的問題。以下轉自他人關於_GUN_SOURCE的部分說明。轉自https://www.cnblogs.com/sky-heaven/p/5649171.html
今天發現一個奇怪的問題,即使
#include sys/stat.h
在使用 lstat 函數的時候還是會報
warning: implicit declaration of function 'lstat'
另外同樣的問題,即使include 了 sys/time.h
還是會報
warning: implicit declaration of function 'nanosleep'
同樣,即使include 了 sys/time.h time.h
warning: implicit declaration of function 'clock_gettime'
error: 'CLOCK_MONOTONIC' undeclared (first use in this function)
最后發現 sys/time.h sys/stat.h time.h 都include 一個共同的頭文件 features.h
原來這是用來讓用戶配置編譯環境的頭文件。再看一下_GUN_SOURCE這個宏,這個宏可以讓用戶打開所有feature.
/* If _GNU_SOURCE was defined by the user, turn on all the other features. */
#ifdef _GNU_SOURCE
# undef _ISOC99_SOURCE
# define _ISOC99_SOURCE 1
# undef _POSIX_SOURCE
# define _POSIX_SOURCE 1
# undef _POSIX_C_SOURCE
# define _POSIX_C_SOURCE 200112L
# undef _XOPEN_SOURCE
# define _XOPEN_SOURCE 600
# undef _XOPEN_SOURCE_EXTENDED
# define _XOPEN_SOURCE_EXTENDED 1
# undef _LARGEFILE64_SOURCE
# define _LARGEFILE64_SOURCE 1
# undef _BSD_SOURCE
# define _BSD_SOURCE 1
# undef _SVID_SOURCE
# define _SVID_SOURCE 1
# undef _ATFILE_SOURCE
# define _ATFILE_SOURCE 1
#endif
因此解決問題的辦法很簡單
只要在source file的開頭 加上
#define _GNU_SOURCE
就可以了。
另外必須注意include 的先后次序
#include time.h
#include sys/time.h
順序搞反了的話 clock_gettime CLOCK_MONOTONIC 是編譯無法通過的。這是因為time.h是標准頭文件
,而sys/time.h 是你當前系統的頭文件。