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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7581408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:44:26  来源:igfitidea点击:

Including a header file from another directory

ccompiler-errorsincludec-preprocessor

提问by Manny

I have a main directory Awith two sub directories Band C.

我有一个A包含两个子目录的主目录BC.

Directory Bcontains a header file structures.c:

目录B包含一个头文件structures.c

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

Directory Ccontains main.ccode:

目录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;
}

But I get an error:

但我收到一个错误:

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)

What is the correct way to include the structures.hfile into main.c?

structures.h文件包含到main.c.

回答by Constantinius

When referencing to header files relativeto your c file you should use #include "path/to/header.h"

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

The form #include <someheader.h>is only used for internal headers or for explicitly added directories (in gcc with the -Ioption).

该表单#include <someheader.h>仅用于内部标题或显式添加的目录(在带有-I选项的gcc 中)。

回答by Jeegar Patel

write

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

in place of

代替

#include <structures.h>

then go in directory in c & compile your main.c with

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

gcc main.c

回答by Timandi Vlad

If you work on a Makefile project or simply run your code from command line, use

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

gcc -IC main.c

gcc -IC main.c

where -Ioption adds your Cdirectory to the list of directories to be searched for header files, so you'll be able to use #include "structures.h"anywhere in your project.

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

回答by Vishwajeet Vishu

If you want to use the command line argument then you can give gcc -idirafter ../b/ main.c

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

then you don't have to do any thing inside your program.

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