# add_lua_package( # ROOT # directory the Lua module names are relative to # MODULES [b.lua ...] # [OUTPUT_DIR ] # where the .hpp/.cpp files are generated # [NAMESPACE ]) # C++ namespace prefix, also prefixes Lua module names # # Creates an OBJECT library holding the compiled Lua modules. Link it # into an executable to make the modules part of the binary: # # add_lua_package(my_lua ROOT lua MODULES mathx.lua pkg/util.lua) # target_link_libraries(my_app PRIVATE my_lua) # # The OBJECT library is used (instead of a static library) so that every module # translation unit is kept, including the ones only reachable through `require`. function(add_lua_package target) cmake_parse_arguments(ARG "" "ROOT;OUTPUT_DIR;NAMESPACE" "MODULES" ${ARGN}) if(NOT ARG_MODULES) message(FATAL_ERROR "add_lua_package(${target}): MODULES is required") endif() if(NOT TARGET luacpp) message(FATAL_ERROR "add_lua_package(${target}): the 'luacpp' executable target is required") endif() if(NOT ARG_ROOT) set(ARG_ROOT "${CMAKE_CURRENT_SOURCE_DIR}") endif() get_filename_component(_root "${ARG_ROOT}" ABSOLUTE) if(ARG_OUTPUT_DIR) get_filename_component(_out "${ARG_OUTPUT_DIR}" ABSOLUTE) else() set(_out "${CMAKE_CURRENT_BINARY_DIR}/luacpp_${target}") endif() set(_namespace_args "") if(ARG_NAMESPACE) set(_namespace_args --namespace "${ARG_NAMESPACE}") endif() set(_sources "") foreach(_module IN LISTS ARG_MODULES) get_filename_component(_abs "${_module}" ABSOLUTE BASE_DIR "${_root}") if(NOT EXISTS "${_abs}") message(FATAL_ERROR "add_lua_package(${target}): module not found: ${_abs}") endif() file(RELATIVE_PATH _rel "${_root}" "${_abs}") string(REGEX REPLACE "\\.lua$" "" _stem "${_rel}") string(REGEX REPLACE "/init$" "" _stem "${_stem}") set(_hpp "${_out}/${_stem}.hpp") set(_cpp "${_out}/${_stem}.cpp") add_custom_command( OUTPUT "${_hpp}" "${_cpp}" COMMAND luacpp "${_abs}" --root "${_root}" --output "${_out}" ${_namespace_args} DEPENDS "${_abs}" $ COMMENT "luacpp: compiling ${_rel}" VERBATIM) list(APPEND _sources "${_cpp}") endforeach() add_library(${target} OBJECT ${_sources}) target_include_directories(${target} PUBLIC "${_out}") target_link_libraries(${target} PUBLIC luacpp::rt) set_target_properties(${target} PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON POSITION_INDEPENDENT_CODE ON) endfunction()