ctkFunctionCompileSnippets.cmake 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #! Compile code snippets from a given directory
  2. #!
  3. #! This CMake function globs all files called \e main.cpp in the
  4. #! directory given by <code>snippet_path</code> and creates
  5. #! an executable for each found main.cpp.
  6. #!
  7. #! If a \e files.cmake file exists in the same directory where a
  8. #! main.cpp file was found, it is included. This function assumes
  9. #! that the files.cmake file sets a list named \e snippet_src_files
  10. #! containing a list of files which should be compiled into the
  11. #! executable. If no files.cmake file is found, all files in the
  12. #! directory are compiled into the executable.
  13. #!
  14. #! This function uses all additionally passed arguments as link
  15. #! dependencies for the created executable.
  16. #!
  17. function(ctkFunctionCompileSnippets snippet_path)
  18. # get all files called "main.cpp"
  19. file(GLOB_RECURSE main_cpp_list "${snippet_path}/main.cpp")
  20. foreach(main_cpp_file ${main_cpp_list})
  21. # get the directory containing the main.cpp file
  22. get_filename_component(main_cpp_dir "${main_cpp_file}" PATH)
  23. set(snippet_src_files )
  24. # If there exists a "files.cmake" file in the snippet directory,
  25. # include it and assume it sets the variable "snippet_src_files"
  26. # to a list of source files for the snippet.
  27. if(EXISTS "${main_cpp_dir}/files.cmake")
  28. include("${main_cpp_dir}/files.cmake")
  29. set(_tmp_src_files ${snippet_src_files})
  30. set(snippet_src_files )
  31. foreach(_src_file ${_tmp_src_files})
  32. if(IS_ABSOLUTE ${_src_file})
  33. list(APPEND snippet_src_files ${_src_file})
  34. else()
  35. list(APPEND snippet_src_files ${main_cpp_dir}/${_src_file})
  36. endif()
  37. endforeach()
  38. else()
  39. # glob all files in the directory and add them to the snippet src list
  40. file(GLOB_RECURSE snippet_src_files "${main_cpp_dir}/*")
  41. endif()
  42. # Uset the top-level directory name as the executable name
  43. string(REPLACE "/" ";" main_cpp_dir_tokens "${main_cpp_dir}")
  44. list(GET main_cpp_dir_tokens -1 snippet_exec_name)
  45. set(snippet_target_name "Snippet-${snippet_exec_name}")
  46. add_executable(${snippet_target_name} ${snippet_src_files})
  47. if(ARGN)
  48. target_link_libraries(${snippet_target_name} ${ARGN})
  49. endif()
  50. set_target_properties(${snippet_target_name} PROPERTIES
  51. RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/snippets"
  52. ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/snippets"
  53. LIBRARY_OUTPUT_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/snippets"
  54. OUTPUT_NAME ${snippet_exec_name}
  55. )
  56. endforeach()
  57. endfunction()