Use pkg-config if possible when building the ruby extension
diff --git a/src/ruby/ext/grpc/extconf.rb b/src/ruby/ext/grpc/extconf.rb
index 6dd0234..59fa87f 100644
--- a/src/ruby/ext/grpc/extconf.rb
+++ b/src/ruby/ext/grpc/extconf.rb
@@ -54,31 +54,41 @@
   LIBDIR
 ]
 
-# Check to see if GRPC_ROOT is defined or available
-grpc_root = ENV['GRPC_ROOT']
-if grpc_root.nil?
-  r = File.expand_path(File.join(File.dirname(__FILE__), '../../../..'))
-  grpc_root = r if File.exist?(File.join(r, 'include/grpc/grpc.h'))
+def crash(msg)
+  print(" extconf failure: #{msg}\n")
+  exit 1
 end
 
-# When grpc_root is available attempt to build the grpc core.
-unless grpc_root.nil?
+def build_local_c(grpc_lib_dir, root, config)
+  grpc_already_built = File.exist?(File.join(grpc_lib_dir, 'libgrpc.a'))
+  system("make -C #{root} static_c CONFIG=#{config}") unless grpc_already_built
+end
+
+def local_fallback(msg)
+  # Check to see if GRPC_ROOT is defined or available
+  grpc_root = ENV['GRPC_ROOT']
+  if grpc_root.nil?
+    r = File.expand_path(File.join(File.dirname(__FILE__), '../../../..'))
+    grpc_root = r if File.exist?(File.join(r, 'include/grpc/grpc.h'))
+  end
+
+  # Stop if there is still no grpc_root
+  crash(msg) if grpc_root.nil?
+
   grpc_config = ENV['GRPC_CONFIG'] || 'opt'
   if ENV.key?('GRPC_LIB_DIR')
     grpc_lib_dir = File.join(grpc_root, ENV['GRPC_LIB_DIR'])
   else
     grpc_lib_dir = File.join(File.join(grpc_root, 'libs'), grpc_config)
   end
-  unless File.exist?(File.join(grpc_lib_dir, 'libgrpc.a'))
-    system("make -C #{grpc_root} static_c CONFIG=#{grpc_config}")
-  end
+  build_local_c(grpc_lib_dir, grpc_root, grpc_config)
   HEADER_DIRS.unshift File.join(grpc_root, 'include')
   LIB_DIRS.unshift grpc_lib_dir
-end
 
-def crash(msg)
-  print(" extconf failure: #{msg}\n")
-  exit 1
+  dir_config('grpc', HEADER_DIRS, LIB_DIRS)
+  have_library('grpc', 'grpc_channel_destroy')
+  create_makefile('grpc/grpc')
+  exit 0
 end
 
 dir_config('grpc', HEADER_DIRS, LIB_DIRS)
@@ -89,9 +99,18 @@
 $CFLAGS << ' -Wall '
 $CFLAGS << ' -pedantic '
 
-$LDFLAGS << ' -lgrpc -lgpr -lz -ldl'
+grpc_pkg_config = system('pkg-config --exists grpc')
 
-crash('need grpc lib') unless have_library('grpc', 'grpc_channel_destroy')
+if grpc_pkg_config
+  $CFLAGS << ' ' + `pkg-config --static --cflags grpc`.strip + ' '
+  $LDFLAGS << ' ' + `pkg-config --static --libs grpc`.strip + ' '
+else
+  $LDFLAGS << ' -lgrpc -lgpr -lz -ldl'
+end
+
+local_fallback('need gpr lib') unless have_library('gpr', 'gpr_now')
+unless have_library('grpc', 'grpc_channel_destroy')
+  local_fallback('need grpc lib')
+end
 have_library('grpc', 'grpc_channel_destroy')
-crash('need gpr lib') unless have_library('gpr', 'gpr_now')
 create_makefile('grpc/grpc')