包括来自另一个目录的头文件

问题描述 投票:36回答:4

我有一个主目录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的正确方法是什么?

c compiler-errors include c-preprocessor
4个回答
36
投票

当引用相对于c文件的头文件时,你应该使用#include "path/to/header.h"

形式#include <someheader.h>仅用于内部标头或明确添加的目录(在gcc中使用-I选项)。


14
投票

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

代替

#include <structures.h>

然后进入c目录并编译你的main.c

gcc main.c

2
投票

如果您处理Makefile项目或只是从命令行运行代码,请使用

gcc -IC main.c

其中-I选项将您的C目录添加到要搜索头文件的目录列表中,因此您将能够在项目中使用#include "structures.h"anywhere。


1
投票

如果要使用命令行参数,则可以给gcc -idirafter ../b/ main.c

那么你不必在你的程序中做任何事情。

© www.soinside.com 2019 - 2024. All rights reserved.