Trying to compile shader with custom command

I’ve got a simple program in one file (main.cc) that uses a Metal shader. I tried this CMakeLists.txt below, but when I edit the source file (Shaders.metal), it doesn’t rebuild.

I’m trying to tell it to rebuild the Shaders.metallib from Shaders.metal, when the latter changes. And I want to tell it that Shaders.metallib should be built when building the executable.

How do I do this?

The are two commands. One to build the .air file from .metal, the second to build .metallib from .air.


set(TARG myui_samples_bare_metal_tri)
add_executable(${TARG} MACOSX_BUNDLE main.cc Shaders.metallib)
set_target_properties(${TARG} PROPERTIES OUTPUT_NAME bare_metal_tri)
target_link_libraries(${TARG}
  PRIVATE MyUI ${APPKIT_LIB} ${METAL_LIB})

add_custom_command(OUTPUT Shaders.air
  MAIN_DEPENDENCY Shaders.metal
  COMMAND xcrun -sdk macosx metal -c Shaders.metal -o Shaders.air)

add_custom_command(OUTPUT Shaders.metallib
  MAIN_DEPENDENCY Shaders.air
  COMMAND xcrun -sdk macosx metallib Shaders.air -o Shaders.metallib)


Something like this should work:
(I used -E copy to test it, you would want to keep your command lines)

cmake_minimum_required(VERSION 3.24)
project(ProjectName)

set(TARG myui_samples_bare_metal_tri)
add_executable(${TARG} MACOSX_BUNDLE main.cc
  ${CMAKE_CURRENT_BINARY_DIR}/Shaders.air ${CMAKE_CURRENT_BINARY_DIR}/Shaders.metallib)
set_target_properties(${TARG} PROPERTIES OUTPUT_NAME bare_metal_tri)

add_custom_command(OUTPUT Shaders.air
  MAIN_DEPENDENCY Shaders.metal
  COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/Shaders.metal ${CMAKE_CURRENT_BINARY_DIR}/Shaders.air)

add_custom_command(OUTPUT Shaders.metallib
  MAIN_DEPENDENCY Shaders.air
  COMMAND  ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/Shaders.air ${CMAKE_CURRENT_BINARY_DIR}/Shaders.metallib)
1 Like