C++ 如何包含另一个文件夹中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6884983/
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-08-28 20:49:52  来源:igfitidea点击:

How to include a file from another folder?

c++include

提问by Sheldon Allen

In my current project I have separated my class files and my header files. My project structure currently looks like this:

在我当前的项目中,我将类文件和头文件分开了。我的项目结构目前如下所示:

  • Project

    • Source
      • src
        • class1.cpp
        • class2.cpp
      • main.cpp
    • Header
      • include
        • class1.h
        • class2.h
  • 项目

    • 来源
      • 源文件
        • 类1.cpp
        • 类2.cpp
      • 主程序
    • 标题
      • 包括
        • 类1.h
        • class2.h

My problem is that I do not know how to include the header files into the class files. Am I unable to link to headers that are not at the same level or in a child folder? Or is there some way to go from the project root and work my way down? For instance:
#include "Project/Headers/include/class1.h"inside the class1.cpp file

我的问题是我不知道如何将头文件包含到类文件中。我是否无法链接到不在同一级别或子文件夹中的标题?或者有什么方法可以从项目根目录开始向下工作?例如:
#include "Project/Headers/include/class1.h"在 class1.cpp 文件中

回答by Pepe

Assuming you want class1.cpp to include class1.h you would do something like this

假设你想要 class1.cpp 包含 class1.h 你会做这样的事情

#include "../../Header/class1.h"

The ..tells the tells the OS to jump 1 directory up when the compiler asks for the file.

..通知告诉操作系统跳1节目录了当编译器请求的文件。

回答by amit

You need to indicate the include path <the directory containing Project>to your compiler so that the compiler is able to find the included headers. Using gcc, you could use -Ioption, and using visual studio, you could use /I.

您需要指明<the directory containing Project>编译器的包含路径,以便编译器能够找到包含的头文件。使用 gcc,您可以使用-Ioption,使用 Visual Studio,您可以使用/I.

回答by lm5050

I had a very similar problem where my compiler could not find the header with a code::blocks C++ project (same file structure as OP) .

我有一个非常相似的问题,我的编译器找不到带有 code::blocks C++ 项目(与 OP 相同的文件结构)的头文件。

This worked for me:

这对我有用:

#include "../include/class1.h"