Skip to content

CMAKE libraries linking

Related to !232 (merged).

Currently, the general structure of a CMAKE compilation employs two approaches to compile and link libraries (e.g. have a look at yambo/CMakeLists.txt, lib/qe_pseudo/CMakeLists.txt, src/bse/CMakeLists.txt. The goal is to modularize the CMake build and the 2 approaches are:

  1. add_library(${MODULE_NAME}_src OBJECT ${PROCESSED_SOURCES}) This creates an object library that compiles source files into .o and .obj files. No library .a or .so files are created. The advatange of this approach is that compiled objects can be reused in multiple targets via $<TARGET_OBJECTS:${MODULE_NAME}_src>. Initially, I thought of using this advantage to link the modules in src/folders*/ for different executables (yambo, p2y, a2y etc..).

Hence, this approach is ideal for compile once and reuse object final among multiple executables.

N.B.: no target_link_libraries is required.

  1. add_library(${MODULE_NAME}_src ${PROCESSED_SOURCES}) creates a real static or shared library. It creates .a or .so files and stored in BUILD_SHARED_LIBS. Libraries can be linked using target_link_libraries. This is ideal when you want compiled code to be into a linkable ojbect and plan to use the compiled binary as a library.

Small example approach 1

# CMakeLists.txt
#compile foo.c files and create module foo.cpp
add_executable(yambo ${CMAKE_SOURCE_DIR}/src/driver/driver.c)
add_library(${MODULE_NAME}_src OBJECT foo.cpp)
# Use object files in an executable
add_executable(yambo $<TARGET_OBJECTS:foo_src>)

Small example approach 2

# Regular static/shared library
add_library(foo foo.cpp)

# Link library to executable
add_executable(yambo ${CMAKE_SOURCE_DIR}/src/driver/driver.c)
target_link_libraries(yambo PRIVATE foo)

Conclusion and TODO

Right now, I used both approaches depending on what suited the best at the moment. I don't know whether one approach is preferred with respect to the other. Probably, special libraries that have to be compiled by cmake in lib/ should follow approach 2 while modules in src/folders* and similar should follow approach 1. @nicspalla Looking forward to your opinions.

Edited by Riccardo Reho