2011-09-28 271 views
24

頭文件我有一個主目錄A有兩個子目錄BC包括來自其他目錄

目錄B包含頭文件structures.c

#ifndef __STRUCTURES_H 
#define __STRUCTURES_H 
typedef struct __stud_ent__ 
{ 
    char name[20]; 
    int roll_num; 
}stud; 
#endif 

目錄C包含main.c代碼:

#include<stdio.h> 
#include<stdlib.h> 
#include <structures.h> 
int main() 
{ 
    stud *value; 
    value = malloc(sizeof(stud)); 
    free (value); 
    printf("working \n"); 
    return 0; 
} 

但我得到一個錯誤:

main.c:3:24: error: structures.h: No such file or directory 
main.c: In function ‘main’: 
main.c:6: error: ‘stud’ undeclared (first use in this function) 
main.c:6: error: (Each undeclared identifier is reported only once 
main.c:6: error: for each function it appears in.) 
main.c:6: error: ‘value’ undeclared (first use in this function) 

什麼是正確的方法公司將structures.h文件導入main.c

+1

什麼是您使用的編譯器?對於gcc,你應該看看-I標誌(參見手冊頁)。對於其他編譯器檢查文檔。 –

回答

26

當引用到頭文件編譯的main.c 相對到你的c文件你應該使用#include "path/to/header.h"

表格#include <someheader.h>僅用於內部頭文件或明確添加的目錄(在gcc中使用-I選項)。

+1

請注意,這是 - 在理論上 - 平臺/編譯器特定。 「以實現定義的方式搜索指定的源文件。」 (關於'#include'文件的ISO/IEC 9899'') –

11

#include "../b/structure.h" 

代替

#include <structures.h> 

然後在目錄中走在C &與

gcc main.c 
1

如果要使用命令行參數,那麼你可以給gcc -idirafter ../b/ main.c

,那麼你就不必做你的程序內的任何東西。

1

如果你在一個Makefile項目工作,或乾脆運行命令行代碼,使用

gcc -IC main.c

其中-I選項將您C目錄的目錄列表中搜索頭文件,所以您可以在項目的任何地方使用#include "structures.h"