Jairo
Jairo

Reputation: 111

CMake how to include headers without sources?

This is probably a dummy question but I have literally looked at the two first pages of google without success.
I'm writing a header only library and I'm unable to set up correctly the CMake configuration in order that when I build my solution a given main.cpp finds the proper includes.
How can this be accomplished?

EDIT

So I probably should give a little more detailed explanation.
Lets say I have a ./src folder with: ./src/core and ./src/wrappers. Inside each folder I have .h files that needs to be included in a main.cpp file:

#include <src/core/reader.h>

Still when I put in CMakeList.txt something like:

include_directories(src/core)
add_executable(main main.cpp)

I receive a message like: src/core/reader.h no such file or directory.

Upvotes: 9

Views: 4083

Answers (4)

skypjack
skypjack

Reputation: 50540

To be able to use that path, you should refer to the parent directory of src.
Assuming the top level CMakeLists.txt is at the same level of src, you can use this instead:

include_directories(${CMAKE_SOURCE_DIR})

As from the documentation of CMAKE_SOURCE_DIR:

The path to the top level of the source tree.

If src is directly in the top level directory, this should let you use something like:

#include <src/whatever/you/want.h>

That said, a couple of suggestions:

  • I would rather add this:

    include_directories(${CMAKE_SOURCE_DIR}/src)
    

    And use this:

    #include <whatever/you/want.h>
    

    No longer src in your paths and restricted search area.

  • I would probably use target_include_directories instead of include_directories and specify the target to be used for that rules:

    target_include_directories(main ${CMAKE_SOURCE_DIR}/src)
    

    This must be put after the add_executable, otherwise the target is not visible.

Upvotes: 11

Daniel Schepler
Daniel Schepler

Reputation: 3103

Another option which might make sense in some situations would be to create a dedicated target for the header-only library:

add_library(headerlib INTERFACE)
target_include_directories(headerlib INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})

And then to use it:

target_link_libraries(mytarget headerlib)

This has the advantage that if you want to use it in multiple targets, it's easy to do so.

Upvotes: 2

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Just add a include_directories() directive in order to find where your header only library can be found by the target project.


According to your edit. To find

 #include <src/core/reader.h>

You need to add

 include_directories(/full_parent_path_of_src)

Upvotes: 1

grigor
grigor

Reputation: 1624

If I understand your question correctly then in your CMakeLists.txt you need to add include_directories(<DIRECTORY>) for every directory of your header library.

Upvotes: 0

Related Questions