The preferred usage is including <mimalloc.h>, linking with the shared- or static library, and using the mi_malloc API exclusively for allocation. For example,
Or, if you like a single source build, just include src/static.c in the build:
mimalloc uses only safe OS calls (mmap and VirtualAlloc) and can co-exist with other allocators linked to the same program.
The model of using the mi_ prefixed API is not always possible though in existing programs that already use the standard malloc interface, and another option is to override the standard malloc interface completely and redirect all calls to the mimalloc library instead.
If you use cmake, you can simply use:
in your CMakeLists.txt to find a locally installed mimalloc. Then use either:
to link with the shared (dynamic) library, or:
to link with the static library. See the test targets in CMakeLists.txt for examples.
With the vcpkg package manager you can add mimalloc to a project with a vcpkg.json manifest as:
or install it globally with vcpkg install mimalloc. Use mimalloc[override] to override the standard malloc, or mimalloc[secure] for secure mode. Use it from cmake as:
When linking statically, enable C++ in your project (e.g. project(main C CXX)) since the port may compile mimalloc as C++. The port is maintained in the vcpkg repository; please open an issue or pull request there if it is out of date. See contrib/vcpkg to build a custom variant of the port.
For best performance in C++ programs, it is also recommended to override the global new and delete operators. For convenience, mimalloc provides mimalloc-new-delete.h which does this for you – just include it in a single(!) source file in your project. Do not include it when statically overriding (e.g. linking with mimalloc.o), as that already defines these operators (unless mimalloc is built with -DMI_OVERRIDE_CXX=OFF).
In C++, mimalloc also provides the mi_stl_allocator struct which implements the std::allocator interface. For example:
The contrib/rust crate builds mimalloc from the sources and can be used as the global allocator:
Build options are enabled as features (e.g. features = ["secure_basic"]), or passed as C defines in the MIMALLOC_DEFINES environment variable. The crate also provides first-class heaps and arenas. See contrib/rust/README.md for details.
The Package.swift package (Swift 6.2 or later, on Linux or macOS) builds mimalloc from the sources and, by default, overrides Basic Allocation for the whole process. Add the product to an executable target:
Build options are selected with traits (e.g. traits: ["Override", "SecureBasic"]), or passed as C defines in the MIMALLOC_DEFINES environment variable. On Windows, use the dynamic override instead. See contrib/swift/README.md for details.
When mimalloc is built using debug mode (-DCMAKE_BUILD_TYPE=Debug), or with -DMI_DEBUG=ON explicitly, various checks are done at runtime to catch development errors.