Search code examples
c++qtinclusion

Qt Including Files in Different Directories


So I've read a few posts and articles about how to go about doing this and one option was to do:

#include "../file/file.h"

But when I use this method, it still cannot find the file. The other way was to add the root of the project to the include path.

So here is an example directory:

main_dir
   - dir2
      -dir3
        -header.h
   -dir4
      -dir 5
        -source.cpp

So if I am trying to include header.h from source.cpp, how do I do this?

My .pro file

#-------------------------------------------------
#
# Project created by QtCreator 2015-02-17T12:52:00
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = project1
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp \
    dir4/dir 5/source.cpp \

HEADERS  += mainwindow.h \
    dir2/dir3/header.h

FORMS    += mainwindow.ui

Solution

  • There are many ways to solve the problem.

    1. Use #include "../../dir2/dir3/header.h" in source.cpp.

    2. If you can add main_dir to the list of include directories, (-I<main_dir_path>), then you can use #include "dir2/dir3/header.h" in source.cpp.

    3. If you can add the toplevel directories under main_dir -- main_dir/dir2 and main_dir/dir4 -- to the list of include directories, then you an use #include "dir3/header.h" in source.cpp.