[CMake] static library from several subdirectories

Michael Wild themiwi at gmail.com
Wed Mar 17 01:59:36 EDT 2010


On 16. Mar, 2010, at 22:30 , Verweij, Arjen wrote:

> Hi Markus,
> 
> I have tested Michael's suggestion. It works wonders for combining source files into a single lib, regardless of the directory levels. For instance, I tested with:
> 
> CMakeLists.txt
> a/CMakeLists.txt
> a/liba.c
> b/CMakeLists.txt
> b/b/CMakeLists.txt
> b/b/libb.c
> 
> Just keep add_subdirectory()'ing until you can add_sources( yourlib [sources] ). So if you have FORTRAN source, you should be done.
> 
> I don't have FORTRAN source, but .fr .f90r .cppr .cr .hr files that need to be preprocessed with fpp to obtain the resulting .f .f90 .cpp .c .h files, which can be used in add_sources(). This seem to cause problems with the setup I had so far, since I get the error:
> 
>  add_dependencies Adding dependency to non-existent target: bar3d
> You have called ADD_LIBRARY for library madymo3d without any source files. This typically indicates a problem with your CMakeLists.txt file
> 
> If I manage to solve it I will report back here.
> 
> Regards,
> Arjen
> 

I'd recommend to change the add_sources function to do all the preprocessing and then only add the products (.f, .f90, .c etc.) files to the list. You can do the preprocessing like this (of course, you'll have to change things for your setup, perhaps even do different things depending on filename extension etc.)

find_program(FPP_EXECUTABLE fpp)
if(NOT FPP_EXECUTABLE)
  message(SEND_ERROR "Failed to find fpp")
endif()

set(SRCS)
foreach(src IN LISTS ARGN)
  get_filename_component(abs_src "${src}" ABSOLUTE)
  file(RELATIVE_PATH rel_src "${CMAKE_CURRENT_SOURCE_DIR}" "${abs_src}")
  set(pre "${CMAKE_CURRENT_BINARY_DIR}/${rel_src}")
  add_custom_command(OUTPUT "${pre}"
    COMMAND ${FPP_EXECUTABLE} "${abs_src}" -o "${pre}"
    WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
    COMMENT "Creating ${pre}"
    VERBATIM
    )
  list(APPEND SRCS "${pre}")
endforeach()
set_property(GLOBAL APPEND PROPERTY "${target}_SRCS" "${SRCS}")



Michael



More information about the CMake mailing list