CMake how to include headers without sources?

筅森魡賤 提交于 2019-12-10 17:26:58

问题


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.


回答1:


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.




回答2:


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)



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/40223903/cmake-how-to-include-headers-without-sources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!