goodman
goodman

Reputation: 516

Adding the header file folder path in a CMake file

I am using CMake in my project and build tree structure is like this tree view of my system:

tree
.
├─ src
├── CMakeLists.txt
├─ CMakeLists.txt

I have .cpp and .h that both are present in the src folder. So while updating the project structure, the new folder structure is this:

tree
.
├─ src
├── CMakeLists.txt
├─ inc
├── headers
├─── file.h
├─ CMakeLists.txt

Now I moved the header files to the inc folder and updated the CMakeLists.txt as below:

include_directories(../inc)
set(HEADERS  ../inc/headerfilename)

add_library(
            libraryName OBJECT
            ${HEADERS}
            application.cpp )


 target_include_directories(libraryName
                            PUBLIC
                            ${CMAKE_CURRENT_SOURCE_DIR}/../inc
                           )

Now while running CMake I am getting compilation error as:

interrupt.h: No such file or directory
#include "interrupt.h"

What could the problem be?

Edit: The top-level CMakeLists.txt file contains the following lines.

cmake_minimum_required(VERSION 3.4)
add_subdirectory(src)

Upvotes: 1

Views: 7516

Answers (3)

Kevin
Kevin

Reputation: 18333

You could make use of CMAKE_SOURCE_DIR, which points to the root of your CMake source tree. Then, use target_include_directories() to add each include directory for your target. Here is your updated src/CMakeLists.txt file:

add_library(libraryName OBJECT
            application.cpp
            )

 target_include_directories(libraryName
                            PUBLIC
                            ${CMAKE_SOURCE_DIR}/inc
                            ${CMAKE_SOURCE_DIR}/inc/folder1
                            ${CMAKE_SOURCE_DIR}/inc/folder2
                            ...
                            )

Note: Adding the headers in add_library() (with your HEADERS variable) is only necessary if you want them to appear with the rest of your sources in an IDE. This step should not be necessary for successful compilation.

Upvotes: 2

goodman
goodman

Reputation: 516

Changed top level CMakeLists.txt as

cmake_minimum_required(VERSION 3.4)
include_directories(inc/headers)
add_subdirectory(src)

Upvotes: 2

Manthan Tilva
Manthan Tilva

Reputation: 3277

Change your top level CMakeLists.txt

cmake_minimum_required(VERSION 3.4)
include_directories(inc)
add_subdirectory(src)

Upvotes: 2

Related Questions