Building a Library with Metal's Command-Line Tools

Use command-line tools to run the Metal compiler toolchain.


Manually compiling Metal Shading Language source code and building a Metal library without using Xcode involves the following process:

  1. Use the metal tool to compile each .metal file into a single .air file, which stores an intermediate representation of Metal Shading Language source code.

  2. Optionally, use the metal-ar tool to archive several .air files together into a single .metalar file. (The metal-ar tool is similar to the UNIX ar tool.)

  3. Use the metallib tool to build .air or .metalar files into a single .metallib file, which stores the Metal library.

A system diagram that shows the steps in the Metal compiler toolchain process.

Run Metal's Command-Line Tools

The following code shows the minimum number of commands that you need to compile and build a single .metal file into a single .metallib file. You can run these commands in the Terminal app and use the -help command to display the available options for each Metal tool. This example uses the macosx SDK, but you can use the iphoneos or appletvos SDK instead.

xcrun -sdk macosx metal -c MyLibrary.metal -o MyLibrary.air
xcrun -sdk macosx metallib MyLibrary.air -o MyLibrary.metallib

Retrieve and Access a Built Library

After you've built a library with Metal's command-line tools, add the resulting .metallib file to your Xcode project. Then, at runtime, call the newLibraryWithFile:error: method to retrieve and access your library as a MTLLibrary object.

NSError *libraryError = NULL;
NSString *libraryFile = [[NSBundle mainBundle] pathForResource:@"MyLibrary" ofType:@"metallib"];
id <MTLLibrary> myLibrary = [_device newLibraryWithFile:libraryFile error:&libraryError];
if (!myLibrary) {
    NSLog(@"Library error: %@", libraryError.localizedDescription);

See Also


Understanding the Metal Shading Language Filename Extension

Use the .metal filename extension to gain access to Metal's build, profile, and debug tools.


A collection of Metal shader functions.


Compilation settings for a Metal shader library.