zono zono -4 years ago 125
C++ Question

CMake How to set src root directory so that always finding header files from root directory instead of relative path?

I have an issue about including header file.

Error Message

In file included from /path/to/src/main.cpp:1:
/path/to/src/dirA/testA.h:1:10: fatal error: 'common/util.h' file not found
#include "common/util.h"


directory

├── dirA
│ └── testA.h
├── common
│ └── util.h
└── main.cpp


main.cpp

#include "dirA/testA.h"

int main()
{}


testA.h

#include "common/util.h" // <--- Here is the error point


CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

add_definitions("-std=c++11")

add_executable(main
main.cpp
)


I found that the following way is fine but I don't want to think the file path relation.

#include "../common/util.h"





Update 1

Thanks to Mark Farrugia's answer, the build error was solved. However, I like "common/util.h" better than "util.h" since the path is easy to understand. And it might to avoid duplicated definitions.

testA.h

#include "util.h"


CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

add_definitions("-std=c++11")

include_directories("common")

add_executable(main
main.cpp
)

Answer Source

Use CMake's include_directories command.

https://cmake.org/cmake/help/v3.0/command/include_directories.html

The following will include all files in the common directory project-wide:

include_directories(common);

Use this as:

#include <util.h>

Or if you want to use the folder in the #include directive:

include_directories(.)

This way you can do the following:

#include <common/util.h>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download