[CMake] The right way to link a library from multiple directories

Sebastian Krause sebastian at realpath.org
Thu Jul 24 11:42:40 EDT 2008


Hello,

I have a library where the files are spread over several
directories, but in the end have to be linked all together into a
single library:

,----
| In src:
|    a.cpp b.cpp c.cpp
| In src/foo:
|    k.cpp l.cpp m.cpp
| in src/bar:
|    x.cpp y.cpp z.cpp
`----

The easiest way to apporach this would be to define everything in a
single CMakeLists.txt in src that does everything at once:

,----
| (set src a.cpp b.cpp c.cpp)
| (set foo foo/k.cpp foo/l.cpp foo/m.cpp)
| (set bar bar/x.cpp bar/y.cpp bar/z.cpp)
| add_library(mylib SHARED ${src} ${foo} ${bar})
`----

However, I don't like this approach because it doesn't fullfill the
following conditions I would like to have:

- There should be a CMakeLists.txt in each subdirectory where I only
  define the files which are in this directory. Additionally I would
  like to be able to set different compile flags for each
  subdirectory.
- The directory structure should stay the same if displayed e.g. in
  Visual Studio. In the first approach, every file would be
  displayed in the same project no matter of its location.

So my first idea was to build the foo and bar subdirectories as
static libraries and link them together later:

,----
| In src/foo/CMakeLists.txt:
|    add_library(foo STATIC k.cpp l.cpp m.cpp)
| In src/bar/CMakeLists.txt:
|    add_library(bar STATIC x.cpp y.cpp z.cpp)
| In src/CMakeLists.txt:
|    add_subdirectory(foo)
|    add_subdirectory(bar)
|    add_library(mylib SHARED ${src})
|    target_link_libraries(mylib foo bar)
`----

Is that the right way to go or do I have to expect some problems in
this case and is there a better way? Some first tests seem to have
no problem using this approach.

However, when I replace the SHARED in mylib with STATIC,
target_link_libraries() doesn't seem to work anymore, so not
everything will be liked together correctly into a static
library. What can I do in this case?

Sebastian



More information about the CMake mailing list