How to include a file from another folder?

2019-03-15 04:23发布

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

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

标签: c++ include
3条回答
孤傲高冷的网名
2楼-- · 2019-03-15 04:53

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) .

This worked for me:

#include "../include/class1.h"
查看更多
劫难
3楼-- · 2019-03-15 04:56

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

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

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

查看更多
家丑人穷心不美
4楼-- · 2019-03-15 04:56

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 -I option, and using visual studio, you could use /I.

查看更多
登录 后发表回答