2011-09-28 267 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"