How to detect if allocator present at compile-time?

Is there a way to tell, at compile-time, if a target supports heap-allocated memory? In general, not testing for a specific allocator.

Conditional compilation options I've considered:

  • #[cfg(any(target_family = "windows", target_family = "unix"))] - assume that a mainstream OS implies heap allocator.

  • #[cfg(any(target_env = "gnu", target_env = "msvc", target_env = "musl", target_env = "uclibc"))] - assume userspace standard library support implies heap allocator.

    • Same false negative as before.
    • Per the docs linked above: "...on many GNU platforms, this value will be empty". So not reliable for this purpose.

There doesn't seem to be a target_feature for heap allocators? Not sure where to find a comprehensive list of possible values.

Any ideas?

I would suggest, especially if this is a library crate, make the dependancy on alloc optional, and use cfg(feature = alloc)

This let's your consumers tell you if they have an allocator or not. I believe the compile will fail if you have the alloc crate in your dependency tree and an allocator has not been provided (by std or manually).

If it's a binary, then you should know if you have an allocator or not (either you have std or are providing one yourself) and can make a feature flag to that effect.


That's a great solution/best practice, thank you!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.