2012-01-03 13 views
3

爲什麼在Ubuntu中構建這個程序時會產生語法錯誤?time_t st_mtime行的語法錯誤?

#include "stdio.h" 
#include "stdlib.h"  
#include "string.h"  
#include "time.h" 
#include "sys/types.h" 
#include "sys/stat.h" 

int main() 
{ 
    time_t st_mtime; 
    printf("Hello\n"); 
    return 0; 
} 

這裏就是我得到的,當我試圖建立這樣的:

$ gcc -o test1 test1.c 
test1.c: In function ?main?: 
test1.c:10: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?.? token 
test1.c:10: error: expected expression before ?.? token 

檢查預處理器輸出:

$ gcc -E test1.c > test1.d 

顯示行10:

time_t st_mtim.tv_sec; 

的只有當我包含「sys/stat」時纔會出現錯誤.h「&」time.h「文件。

+1

'「'只對本地文件。這些應該是'#包括',等等。 – Dave 2012-01-03 14:40:26

+2

st_mtime可能是一個預處理宏象'#定義st_mtime time_array [XXXX]'。和名字的前綴是' st_'有一個原因... – wildplasser 2012-01-03 14:44:51

回答

5

如果grep/usr/includest_mtime,你會發現如下:

$ grep -r st_mtime /usr/include | grep define 
/usr/include/x86_64-linux-gnu/bits/stat.h:# define st_mtime st_mtim.tv_sec 

所以問題是由使用的變量名st_mtime的莖。

+0

這使得它不能用於通用目的,它充當'C'保留字。是否還有更多這種類型的文件? – user1054965 2012-01-03 15:08:07

+0

@ user1054965:很多,在頭文件中。 t認爲你可以全部瞭解它們,但是如果你有這樣一個奇怪的問題,試着改變變量名稱作爲調試步驟並沒有什麼壞處。:) – 2012-01-03 15:09:29

+1

POSIX記錄各種頭文件的保留字。對於stat .h','st_ *'在保留的命名空間中,所以你不能自己使用它。 – 2012-01-03 18:29:06