Use cfg to modify link attribute


In my rust library I have

#[link(name = "stdc++")]

to link in the c++ libraries that some external code needs to run. This works great and I have built linux executables that work.

However, I found that on new mac OS’s libstdc++ is present and instead you need to link libc++ (see and thus my question is this:

How can I use a cfg attribute to link libstd++ on linux and libc++ on macos?

There’s #[cfg_attr(condition, attr)] that applies attributes conditionally.

Additionally, the cc crate has support for compiling and linking C++ code, and AFAIK it can choose the right stdlib automatically.

1 Like

Thanks #[cfg_attr(condition, attr)] was exactly what I was looking for :slightly_smiling_face:

The cc crate was exactly what I wasn’t looking for but should have been! I have just tested replacing



#[cfg_attr(target_os = "macos", link(name = "c++"))]
#[cfg_attr(not(target_os = "macos"), link(name = "stdc++"))]

and it works like a charm. When I get some time I will try out the cc create :tada: