【问题标题】:Including a header file from another directory包含来自另一个目录的头文件
【发布时间】:2011-11-26 17:46:29
【问题描述】:

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

【问题讨论】:

  • 您使用的编译器是什么?对于 gcc,您应该查看 -I 标志(请参阅手册页)。对于其他编译器,请查看文档。

标签: c compiler-errors include c-preprocessor


【解决方案1】:

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

#include &lt;someheader.h&gt; 形式仅用于内部标头或显式添加的目录(在 gcc 中使用 -I 选项)。

【讨论】:

  • 请注意,这在理论上是特定于平台/编译器的。 “以实现定义的方式搜索命名的源文件。” (ISO/IEC 9899 关于'#include "file"')
【解决方案2】:

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

代替

#include <structures.h>

然后进入 c 目录并用

编译你的 main.c
gcc main.c

【讨论】:

    【解决方案3】:

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

    gcc -IC main.c

    其中-I 选项将您的C 目录添加到要搜索头文件的目录列表中,因此您可以在项目中的任何地方使用#include "structures.h"

    【讨论】:

      【解决方案4】:

      如果你想使用命令行参数,那么你可以给gcc -idirafter ../b/ main.c

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

      【讨论】:

        猜你喜欢
        • 2014-03-17
        • 2013-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多