Cannot Install ‘pg’ gem in Mac OSX – Error installing pg: ERROR: Failed to build gem native extension — Ruby on Rails

If you are planning on using PostgreSQL with Ruby on Rails, you will need to install pg, which is the Ruby interface to the PostgreSQL RDBMS. The command to install it is as follows:

$ gem install pg

However, before you run that command you need to install PostgreSQL. After installing PostgreSQL and run the above command to install pg, if you get the below error, keep reading 🙂

esilva@Esau-MBP:Website$ sudo gem install pg
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
	ERROR: Failed to build gem native extension.

    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -r ./siteconf20141101-13676-mwatig.rb extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:

extconf failed, exit code 1

Gem files will remain installed in /Library/Ruby/Gems/2.0.0/gems/pg-0.17.1 for inspection.
Results logged to /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-13/2.0.0/pg-0.17.1/gem_make.out

Well, this is because pg needs pg_config to install (you get pg_config when you install PostgreSQL). To find pg_config run the below command, then copy the path

$ sudo find / -name "pg_config"

After you find pg_config location, run the below command to finally install pg gem. Remember to add — –with-pg-config=/path/to/pg_config gem option

esilva@Esau-MBP:~/AAA_Website$ sudo gem install pg -- --with-pg-config=/Library/PostgreSQL/9.3/bin/pg_config
Building native extensions with: '--with-pg-config=/Library/PostgreSQL/9.3/bin/pg_config'
This could take a while...
Successfully installed pg-0.17.1
invalid options: -f fivefish
(invalid options are ignored)
Parsing documentation for pg-0.17.1
Installing ri documentation for pg-0.17.1
Done installing documentation for pg after 1 seconds
1 gem installed

You have successfully installed pg gem


Esau Silva
Software Engineer at Region One ESC
Full Stack Software Engineer working with Microsoft technologies, ReactJS is awesome and avid Brazilian Jiu-Jitsu practitioner
Spread the love

4 thoughts on “Cannot Install ‘pg’ gem in Mac OSX – Error installing pg: ERROR: Failed to build gem native extension — Ruby on Rails

  1. Jeremy says:

    After running sudo find / -name “pg_config” I get the following:
    find: /dev/fd/3: Not a directory
    find: /dev/fd/4: Not a directory

    nothing else 🙁

  2. Allan Xavier says:

    Thanks for the post!! It worked for me!!

Leave a Reply

Your email address will not be published. Required fields are marked *