2011-05-07 78 views
3

我有一個函數,CREATEFILE使用fchmod的隱式聲明:C警告:函數 'fchmod'

int createFile(char *pFileName) { 
    int ret; 

    if ((ret = open(pFileName, O_RDWR | O_CREAT | O_TRUNC)) < 0) 
     errorAndQuit(2); 

    fchmod(ret, S_IRUSR | S_IWUSR); 
    return ret; 
} 

在我的文件的頂部,我有以下包括:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/stat.h> 
#include <fcntl.h> 

編譯時:編譯器吐出:

warning: implicit declaration of function ‘fchmod’ 

我包括所有正確的文件,但得到此警告。程序運行良好,即使有警告。

+0

警告不是錯誤。 – Falmarri 2011-05-07 01:27:40

+5

@Falmarri不,但他們傾向於告訴你代碼可能有問題。傾聽他們的想法是個好主意。 – 2011-05-07 01:31:14

+0

@Falmarri是的,我知道。不過,使用-Wall進行編譯並不會有任何警告......並且我從來沒有說過我正在嘗試糾正錯誤 – itzhero 2011-05-18 16:25:18

回答

4

可巧,你的問題是直接由feature_test_macros(7)手冊頁回答:

Specification of feature test macro requirements in manual pages 
    When a function requires that a feature test macro is 
    defined, the manual page SYNOPSIS typically includes a note 
    of the following form (this example from the chmod(2) manual 
    page): 

      #include <sys/stat.h> 

      int chmod(const char *path, mode_t mode); 
      int fchmod(int fd, mode_t mode); 

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

      fchmod(): _BSD_SOURCE || _XOPEN_SOURCE >= 500 

    The || means that in order to obtain the declaration of 
    fchmod(2) from <sys/stat.h>, either of the following macro 
    definitions must be made before including any header files: 

      #define _BSD_SOURCE 
      #define _XOPEN_SOURCE 500  /* or any value > 500 */ 

    Alternatively, equivalent definitions can be included in the 
    compilation command: 

      cc -D_BSD_SOURCE 
      cc -D_XOPEN_SOURCE=500  # Or any value > 500 
2

您沒有指定您正在使用的編譯器或平臺,但是在我最近的Linux安裝中,fchmod()被定義在一些#ifdefs(__USD_BSD和__USE_XOPEN_EXTENDED)中,但被保護。

你不應該直接設置它們,而是通過_FOO_SOURCE宏來設置它們。嘗試定義_XOPEN_SOURCE_EXTENDED或僅僅_GNU_SOURCE並重新編譯(並注意這些宏啓用非標準功能並使用它們啓用的功能可能會限制代碼的可移植性)。

0

同時建立UML我面臨這個錯誤。
在文件中只需添加這條線,其中引發此錯誤:

#include "sys/stat.h" 

我相信它會照顧有關添加上述答案定義的宏。