user3063750
user3063750

Reputation: 903

How do I add an include directory from outside the root folder with CMake?

This is my first CMakeLists.txt code:

#cmake_minimum_required (VERSION 2.6)
project (project)

add_subdirectory(src)

include_directories(${/path_to_directory}/include)

And this is the CMakeLists.txt in the subdirectory

set (CMAKE_C_FLAGS "-WALL -g")

file(GLOB SRCS *.cpp *.hpp *.h)

add_executable(source ${SRCS})

I'm still unable to include the path_to_directory in my project

edit: This didn't work either:

file(GLOB mylib *.cpp *.hpp *.h)

add_executable(includeSource ${mystuff})
target_include_directories(
    mystuff
    PUBLIC ${path_to_directory}/include
)

Upvotes: 4

Views: 9186

Answers (2)

cromod
cromod

Reputation: 1819

According to your first two codes, I understand your executable source doesn't compile because your compiler doesn't find the include files from ${/path_to_directory}/include.

On this assumption, I can say you misplaced include_directories(${/path_to_directory}/include), it should be in the CMakeLists.txt of subdirectory.

The documentation of include_directories will help you to understand :

The include directories are added to the INCLUDE_DIRECTORIES directory property for the current CMakeLists file. They are also added to the INCLUDE_DIRECTORIES target property for each target in the current CMakeLists file. The target property values are the ones used by the generators.

Otherwise, you can replace include_directories(${/path_to_directory}/include) by target_include_directories(source PUBLIC ${/path_to_directory}/include) in your main CMakeLists.txt as @skypjack suggest. It'll impact the source target in the CMakeLists.txt of subdirectory.


Additionnal comments and advise

  1. You want to compile c++ source files but you define CMAKE_C_FLAGS and not CMAKE_CXX_FLAGS.

  2. set (CMAKE_C_FLAGS "-Wall -g") is dangerous if you previously set CMAKE_C_FLAGS. Prefer set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -g")

  3. file(GLOB ...) isn't recommended to find source files. See the documentation :

We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate.

  1. If your main CMakeLists.txt is as simple as you show, add_subdirectory is useless. You can do everything in only one main CMakeLists.txt

Upvotes: 1

skypjack
skypjack

Reputation: 50548

Even if the question is not clear, I guess you want target_include_directories (here the documentation) instead of include_directories.

From the documentation:

Specify include directories or targets to use when compiling a given target.

You can use it as:

target_include_directories(
    your_target_name
    PUBLIC ${/path_to_directory}/include
)

Upvotes: 1

Related Questions