How to Fix “Can’t find the ‘libpq-fe.h header when trying to install pg gem”?

In Linux, Ruby on Rail is the scripting programming language that is utilized for creating the applications. Pg gem is the ruby interface to PostgreSQL (RDBMS), which works with the 9.3 or higher version. During the installation of pg in Linux, the user can face the error “Can’t find the ‘libpq-fe.h header”. The reasons and solutions for the given error will be demonstrated in this article.

Reason: libpq-dev Package is Not Installed

The reason for the error given is that you must have to install the “libpq-dev” package (missing headers) to use the ruby interface. “libpq-dev” is the package that contains the set of Postgresql and headers for developing the applications.

Solution: Installing libpq-dev 

To install the “libpq-dev” package, run the following command in the terminal:

$ sudo apt install libpq-dev     #For Debian/Ubuntu
$ yum install postgresql-devel   #For RHEL
$ yum install libpqxx-devel      #For CentOS
$ pacman -S postgresql-libs      #For Arch

The “libpq-dev” library will be installed.

Alternate Solution: Installing ruby-dev

Another possible solution to resolve the error is to install the ruby-dev package. “ruby-dev” is the package that also contains headers files for ruby:

$ sudo apt install ruby-dev

The ruby-dev is installed.

Now you can install pg gem in your operating system:

$ sudo gem install pg

The pg gem is successfully installed.

Conclusion 

The reason for the error ”Can’t find the ‘libpq-fe.h header” is that headers are not installed. To fix this error, install the header “sudo apt install libpq-dev” or “sudo apt install ruby-dev” command. This post has illustrated the reasons and solutions for the given error.