關於__GNU_SOURCE 這個宏---如何開啟【轉】


今天發現一個奇怪的問題,即使
#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 是你當前系統的頭文件。

 
 
如何開啟_GNU_SOURCE宏
轉自: http://blog.csdn.net/satanwxd/article/details/6234577

在編寫網絡程序時,會涉及到一些關於BSD系統保留下的結構體和宏定義,關於一切配置在linux系統的/usr/include/features.h文件中,開啟項如下:

#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        199506L
# 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
#endif
可以看出只要開啟了_GNU_SOURCE的花,大部分的BSD功能可以打開,看看_GNU_SOURCE是否開啟有一個測試程序:

#include <iostream>

int main()
{
#ifdef _GNU_SOURCE
  std::cout << "gnu/n";
#else
  std::cout << "non-gnu/n";
#endif
}
只要gcc -D _GNU_SOURCE test.c -o test.o編譯生成的text.o文件,運行一下就知道是否開啟了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM