Add a dependency not in a subdirectory using CMake

Go To StackoverFlow.com

13

Let's say there's following directory structure:

root
  |
  +--projects
  |      |
  |      +-test
  |         |
  |         +-CMakeFiles.txt
  |
  +--libs
       |
       +-testlib
            |
            +-CMakeFiles.txt

test contains CMakeFiles.txt and testlib also contains CMakeFiles.txt. "test" produces an executable and "testlib" produces a static library.

I want "test" to link with "testlib" without using symlinks and without moving "testlib" library into a subdirectory within "test".

Because "testlib" isn't a subdirectory of "test", I can't do

add_subdirectory("../../libs/testlib")

In test's CMakeFiles.txt - CMake will complain about "testlib" not being in the "test" subdirectory.

Also, because system has several different compilers, I can't simply install "testlib" libraries into some kind of central directory, so I want test to compile a local copy of testlib and link with it (i.e. as if testlib was a subdirectory). I also want the "test" project to automatically rebuild "testlib" if it has been changed.

So, how can I deal with it? I am using CMake 2.8.4 on Windows XP SP3.

2012-04-04 02:18
by SigTerm


16

You could either provide a top-level CMakeLists.txt in root, or provide a binary directory to the add_subdirectory command; e.g.

add_subdirectory("../../libs/testlib" "${CMAKE_CURRENT_BINARY_DIR}/testlib_build")

This creates a subdirectory called testlib_build in your current build directory which contains the generated project files for testlib, but not the source.

For further info, run

cmake --help-command ADD_SUBDIRECTORY
2012-04-04 08:52
by Fraser
Thanks - that's exactly what I needed - SigTerm 2012-04-04 13:00
@Fraser - Is it possible to specify binary directory in testlib_build's CMakeFile - tower120 2015-08-09 18:49
@tower120 - No, you'd need to specify it in the add_subdirectory call - Fraser 2015-08-14 00:10


12

The only way I see to do this - create CMakeLists.txt in root and put the following code there:

add_subdirectory(projects/test)
add_subdirectory(lib/testlib)

When you have done this, you can do target_link_libraries(test testlib) in test/CMakeLists.txt, and it will be automatically rebuilt if you change something in testlib.

2012-04-04 06:21
by arrowd