使用cairo-rs编译链接失败:找不到-lgobject-2.0库
-lgobject-2.0 When Using cairo-rs on macOS High Sierra Looks like you're hitting a common linker path issue with MacPorts-installed libraries on macOS. Let's break down how to fix this step by step:
1. Install the missing GLib dependencies first
The -lgobject-2.0 error means your linker can't find the GObject library, which is a core part of GLib. Install it via MacPorts if you haven't already:
sudo port install glib2
2. Tell Cargo where to find MacPorts libraries
macOS doesn't automatically include /opt/local/lib (MacPorts' default library directory) in the linker's search path. You have two solid options to fix this:
Option A: Temporary environment variable fix
Run these commands before building your project to add the MacPorts paths to your session:
export LIBRARY_PATH=/opt/local/lib export CPATH=/opt/local/include cargo build
Option B: Permanent build script setup
Create a build.rs file in your project root to hardcode the library paths for Cargo (so you don't have to set variables every time):
fn main() { // Direct Cargo to look for libraries in MacPorts' lib directory println!("cargo:rustc-link-search=native=/opt/local/lib"); // Explicitly link the required libraries println!("cargo:rustc-link-lib=gobject-2.0"); println!("cargo:rustc-link-lib=cairo"); }
Then update your Cargo.toml to use this build script, and upgrade to a newer cairo-rs version (your current 0.4.1 is quite outdated):
[package] # Keep your existing package name/version info here build = "build.rs" [dependencies] png = "0.17.0" cairo-rs = { version = "0.18.0", features = ["png"] }
3. Why this works
MacPorts installs libraries in /opt/local instead of macOS's default /usr/lib, so the Rust linker has no idea to look there unless you explicitly point it. Adding the path via environment variables or a build script fixes that gap. Additionally, newer cairo-rs versions are better maintained and play nicer with modern macOS library setups, which helps avoid compatibility hiccups.
内容的提问来源于stack exchange,提问作者David Sullivan

