diff --git a/Cargo.toml b/Cargo.toml index f8ebfb8..473bfe8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,5 +11,8 @@ build = "build.rs" [lib] name = "pq_sys" +[build-dependencies] +pkg-config = "~0.3" + [dependencies] libc = "0.2.*" diff --git a/README.md b/README.md index 9965a83..f09886c 100644 --- a/README.md +++ b/README.md @@ -10,11 +10,20 @@ This repository contains direct, one-to-one mappings to the C functions provided in `libpq-fe.h` and `postgres_ext.h`. This library expects that libpq be installed on the system. -You may need to specify the environment variable `LIB_PQ_DIR` to the location of -your postgresql lib directory if the build fails. +The build script of crate will attempt to find the lib path of libpq using the +following methods: + +* First, if the environment variable `LIB_PQ_DIR` is set, it will use its value +* If the environment variable isn't set, it tries to use pkg-config to locate it. +All the config options, such as `PKG_CONFIG_ALLOW_CROSS`, `PKG_CONFIG_ALL_STATIC` +etc., of the crate [pkg-config](http://alexcrichton.com/pkg-config-rs/pkg_config/index.html) +apply. +* If it still can't locate the library, it will invoke the Postgres command +`pg_config --libdir` The build script instructs Cargo to link the library statically if the environmental variable `LIB_PQ_STATIC` is set. This can be useful, if targeting for a musl target. +If pkg-config is being used, it's configuration options will apply. For OSX 10.11 you can use brew to install postgresql and then set the environment variable as described below: diff --git a/build.rs b/build.rs index 66cffe1..e1adbe3 100644 --- a/build.rs +++ b/build.rs @@ -1,11 +1,20 @@ +extern crate pkg_config; + use std::fs; use std::path::PathBuf; use std::process::Command; use std::env; fn main() { + let link_flag = "pq"; + let pkg_name = "libpq"; + if let Ok(lib_dir) = env::var("PQ_LIB_DIR") { println!("cargo:rustc-link-search=native={}", lib_dir); + + } else if pkg_config::probe_library(pkg_name).is_ok() { + return // pkg_config does everything for us, including output for cargo + } else if let Some(path) = pg_config_output() { let path = follow_dylib_symlinks(path.trim().into()); println!("cargo:rustc-link-search=native={}", &path.display()); @@ -16,9 +25,8 @@ fn main() { } else { "dylib" }; - let lib = "pq"; - println!("cargo:rustc-link-lib={}={}", mode, lib); + println!("cargo:rustc-link-lib={}={}", mode, link_flag); } fn pg_config_output() -> Option {