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

k2fxgqgv  于 2023-10-16  发布在  其他
关注(0)|答案(5)|浏览(143)

我有一个主目录A和两个子目录BC
目录B包含一个头文件structures.c

  1. #ifndef __STRUCTURES_H
  2. #define __STRUCTURES_H
  3. typedef struct __stud_ent__
  4. {
  5. char name[20];
  6. int roll_num;
  7. }stud;
  8. #endif

目录C包含main.c代码:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include <structures.h>
  4. int main()
  5. {
  6. stud *value;
  7. value = malloc(sizeof(stud));
  8. free (value);
  9. printf("working \n");
  10. return 0;
  11. }

但我得到一个错误:

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

structures.h文件包含到main.c中的正确方法是什么?

2admgd59

2admgd591#

当引用头文件 * 相对于 * 你的c文件,你应该使用#include "path/to/header.h"
格式#include <someheader.h>仅用于内部头或显式添加的目录(在gcc中带有-I选项)。

omvjsjqw

omvjsjqw2#

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

代替

  1. #include <structures.h>

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

  1. gcc main.c
1dkrff03

1dkrff033#

如果您处理Makefile项目或只是从命令行运行代码,请使用
gcc -IC main.c
其中-I选项将您的C目录添加到要搜索头文件的目录列表中,因此您可以在项目中的任何位置使用#include "structures.h"

l2osamch

l2osamch4#

如果您想使用命令行参数,则可以给予gcc -idirafter ../b/ main.c
那么你不需要在程序中做任何事情。

vxf3dgd4

vxf3dgd45#

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include "parent_directory/structures.h>
  4. int main()
  5. {
  6. stud *value;
  7. value = malloc(sizeof(stud));
  8. free (value);
  9. printf("working \n");
  10. return 0;
  11. }

用这个替换你的代码,不要忘记用你的文件所在的文件夹的路径替换parent_directory。我不知道你的文件structures.h是否有.h扩展名或.c,所以请看看它.

相关问题