Installation
You can install MLX in several ways:Install via Python Package
The easiest way is to install the MLX Python package, which includes the C++ libraries:Build from Source
To build just the C++ library from source, see the build and install documentation.CMake Project Setup
Basic Project Structure
Create a project with the following structure:Example Program
Createmain.cpp:
main.cpp
CMakeLists.txt
CreateCMakeLists.txt:
CMakeLists.txt
Finding MLX with CMake
The method to find MLX depends on how you installed it.If Installed via Python Package
Add this to yourCMakeLists.txt before find_package(MLX):
If Installed to System Path
If you built and installed MLX to a system path (like/usr/local), CMake should find it automatically:
If Installed to Custom Location
If you installed MLX to a custom location, setMLX_ROOT:
Building Your Project
CMake Variables
When you callfind_package(MLX CONFIG REQUIRED), the following CMake variables are set:
| Variable | Description |
|---|---|
MLX_FOUND | TRUE if MLX is found |
MLX_INCLUDE_DIRS | Include directories for MLX headers |
MLX_LIBRARIES | Libraries to link against |
MLX_CXX_FLAGS | Additional compiler flags |
MLX_BUILD_ACCELERATE | TRUE if MLX was built with Accelerate support |
MLX_BUILD_METAL | TRUE if MLX was built with Metal support |
Complete Example
Here’s a complete working example:main.cpp
CMakeLists.txt
Linear Regression Example
Here’s a more advanced example showing a complete linear regression implementation:linear_regression.cpp
Key Patterns
Lazy Evaluation
MLX uses lazy evaluation. Callmx::eval() to execute:
Lambda Functions
Use lambdas for function transformations:Namespace Alias
Always use a namespace alias for cleaner code:Common Issues
CMake Can’t Find MLX
If CMake can’t find MLX, try:- Check that MLX is installed:
python -c "import mlx.core" - Verify the Python path:
python -m mlx --cmake-dir - Explicitly set
MLX_ROOTin CMakeLists.txt
Link Errors
If you get undefined symbols:- Make sure you’re using C++20 or later
- Check that you linked with
target_link_libraries(... PRIVATE mlx) - Verify MLX was built with Metal support on macOS
Runtime Errors
If you get runtime errors:- Make sure to call
mx::eval()on arrays before accessing data - Check array shapes match for operations
- Verify data types are compatible
Next Steps
Operations Reference
See all available C++ operations
Build Extensions
Create custom operations in C++
Metal Kernels
Write custom GPU kernels
Examples
Browse more C++ examples