Home > Mobile >  Pretend headers are in a certain subdirectory?
Pretend headers are in a certain subdirectory?

Time:01-23

Note: I'm currently tinkering with more modern CMake styles, not trying to accomodate an existing project. I'd consider alternative approaches to what I am doing as perfectly acceptable as long as they are scalable (i.e., downstream target shouldn't need to know about the internals of the upstream target).

Let's say I have two targets in the same CMake build, down and up, where down depends on up:

target_link_libraries(down PUBLIC up)

Let's say the headers of up are inside up/src/:

 ---up
     ---CMakeLists.txt
     ---src
         ---header.hpp
         ---<other headers/sources>

Now let's say that inside down I want to include the headers of up like so:

// down/foo.cpp

#include "up/header.hpp"

If down is an external dependency (i.e. in a separate CMake build), that's easy: I just have to install all the headers of up in some kind of include/up/ directory and then use that:

target_include_directories(up
  INTERFACE
    "$<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/include/up>")

But what if down is part of the same CMake build as up? I want to uniformize the code; I don't want down's sources to have to do any of...

#include "up/src/header.hpp"
#include "src/header.hpp"
#include "header.hpp"

The headers of up wouldn't be installed inside include/up until after all the targets, including down, would be built, since down is inside the same CMake build.

Is that sort of thing even possible without using horrible manual file copies? Should I just put all up's sources inside a up/src/up/ directory then?

My motivation is: up might be depended on by libraries both inside and outside the CMake build, so I want to uniformize the code accross internal and external targets.

CodePudding user response:

If you want #include "up/header.hpp" to work, then the file header.hpp should be physically located in the directory up. This is how all major compilers work, so CMake simply cannot "emulate" location of a header file.

However, it is quite easy to copy headers into desired directory. E.g. by using file(COPY) command. List of files to copy can be obtained using file(GLOB), like in that answer:

file(GLOB UP_HEADERS /path/to/up/src/*.h)
file(COPY ${UP_HEADERS} DESTINATION /path/to/some/dir/include/up)
  • Related