[CMake] Newbie question: Static linking

Sanatan Rai sanatan at gmail.com
Sun May 22 19:36:14 EDT 2011


Hi folks,
   This  has probably been done to death before, so apologies
in advance.

   I have a project wherein I want all the project libraries to be linked
statically to the final executables.

  I certainly get static libraries when I run make, however, two of
the libraries don't seem to link statically.

 Example: root CMakeLists.txt

  project(myProj)
  add_subdirectory(lib1)
  add_subdirectory(lib2)
  add_subdirectory(helpers)
  add_subdirectory(target)

helpers/CMakeLists.txt:

include_directories(${myProj_SOURCE_DIR})
add_library(helper1 helper1.cpp)
target_link_library(helper1 boost_date_time)
add_library(helper2 helper2.cpp)
target_link_library(helper2 sqlite3)

target/CMakeLists.txt

include_directorues(${myProj_SOURCE_DIR})
add_executable(myTarget target.cpp)
target_link_library(myTarget lib1 lib2 helper1 helper2 boost_iostreams)

After cmake, and make all, the libraries build as static archives, ie I get
liblib1.a, liblib2.a, libhelper1.a, libhelper2.a and executable myProj in the
appropriate locations. However, the executable myProj does not appear
to have linked statically to libhelper1.a and libhelper2.a. These libraries
contain global initialisers for certain objects: which doesn't happen when
I run the executable.

However, if I remove add_subdirectory(helpers) from the root CMakeLists.txt
and change targetCMakeLists.txt to:

include_directorues(${myProj_SOURCE_DIR})
add_executable(myTarget target.cpp helpers/helper1.cpp helpers/helper2.cpp)
target_link_library(myTarget lib1 lib2 boost_date_time boost_iostreams sqlite3)

everything works as expected, ie my objects get initialised.

Why does the second approach work but not the first?

Quite possibly I am missing something very basic here...so apologies in advance!

Platform: gcc 4.4.5-8 on amd64 Debian squeeze, cmake 2.8.2

--Sanatan


More information about the CMake mailing list