[CMake] Linking archives in a sibling directory

Michael Hertling mhertling at online.de
Wed Dec 1 11:03:12 EST 2010


On 12/01/2010 08:18 AM, Raymond Wan wrote:
> Hi all,
> 
> I'm having a problem understanding how I can link to an archive in
> another directory which is not a subdirectory. For example:
> 
> myproj
>   +-- main
>     +-- CMakeLists.txt
>     +-- source files for main program
>   +-- dir-A
>     +-- CMakeLists.txt
>     +-- source files for sub-program A
>   +-- dir-B
>     +-- CmakeLists.txt
>     +-- source files for sub-program B
> 
> 
> Basically, I would like to make a larger project (main) and I'm
> building and testing each of its components separately.
> 
> Right now, the main's CMakeLists.txt looks something like this:
> 
> 
> INCLUDE_DIRECTORIES (../dir-A)
> SUBDIRS (../dir-A)
> ADD_EXECUTABLE (main ${MAIN_SRCS})
> TARGET_LINK_LIBRARIES (main subprogA_ar)
> 
> 
> which works fine so far (the CMakeLists.txt in dir-A generates the
> archive subprogA_ar).
> 
> However, I just found out that SUBDIRS is deprecated and so, replaced
> it with "ADD_SUBDIRECTORY".  That's when I got an error about "dir-A"
> not being a subdirectory.  Obviously, I was not using "SUBDIRS" before
> as it was intended...  :-)

This error is caused by the fact that the directory "dir-A" is outside
the "main" directory tree, so dir-A's binary directory would likewise
be outside main's binary tree, and this is reasonably forbidden when
configuring "main". You might specify dir-A's binary directory in
main/CMakeLists.txt explicitly, e.g.:

ADD_SUBDIRECTORY(../dir-A ${CMAKE_CURRENT_BINARY_DIR}/dir-A)

Hence, subprogA_ar will be built within the binary tree's "dir-A".

> I've also tried adding "dir-A" as a LINK_DIRECTORIES with no success.
> It is unable to find subprogA_ar.
> 
> I'm not sure if it is possible, but ideally, when I run "make" in
> main/, I would like it to rebuild the targets in "dir-A" (including
> the archive) and link that in.
> 
> I'm also open to the possibility that I got the above organization all
> wrong and should have only one large CMakeLists.txt in a directory
> structure like this:
> 
> 
> myproj
>   +-- main
>     +-- CMakeLists.txt
>     +-- source files for main program
>     +-- dir-A
>       +-- source files for sub-program A
>     +-- dir-B
>       +-- source files for sub-program B
> 
> 
> Is this what I should have done??

As an alternative, consider to add a CMakeLists.txt in "myproj"

CMAKE_MINIMUM_REQUIRED(...)
PROJECT(myproj)
ADD_SUBDIRECTORY(dir-A)
ADD_SUBDIRECTORY(dir-B)
ADD_SUBDIRECTORY(main)

and subsequently, configure this directory instead of "main".

Regards,

Michael


More information about the CMake mailing list