How to set LD_LIBRARY_PATH?

In this article, we will set the correct way to set the environment variable LD_LIBRARY_PATH. Additionally, we will see the wrong way to set LD_LIBRARY_PATH (why it is wrong?) and an alternative way using bashrc.

In short, you can use the following command:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/absolute_path/

We will cover the following points in this guide:

  • Set LD_LIBRARY_PATH
  • Wrong way to set LD_LIBRARY_PATH
  • Alternative way using bashrc
  • Example

LD_LIBRARY_PATH is an environment variable that is used to set paths to shared libraries (that is .so files) so that it available during execution of executables.

Set LD_LIBRARY_PATH

The correct way to set LD_LIBRARY_PATH is as follows:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/absolute_path/

Wrong way to set LD_LIBRARY_PATH

The wrong way to set LD_LIBRARY_PATH is:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/absolute_path/

This is because it will override all existing values in LD_LIBRARY_PATH. Hence, if your code depends on multiple libraries which are located at different location, then if all paths are set except one and you set the last path using the above wrong way, then all previous paths are overridden and you need to set all paths again.

This can be tedious if you are setting LD_LIBRARY_PATH manually.

Alternative way using bashrc

Another approach is to add the export command to this file:

~/.bashrc

The advantage of this approach is that the LD_LIBRARY_PATH will be set everytime the shell is opened.

The command to add the LD_LIBRARY_PATH command is as follows:

echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/absolute_path/' >> ~/.bashrc

bashrc is a BASH shell script that is run everything an interactive shell session is started. It is used to:

  • Run commands at the beginning of a shell session
  • Set environment variables (like OMP_NUM_THREADS) at the start of a shell session
  • Set alias for various purposes like make python point to python3

This is how the file "bashrc" looks by default:

export CLICOLOR=1
export LANG="en_US.UTF-8"
alias cp="cp -i"
alias ls="ls --color=auto"
export PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "
export EDITOR="vim"

Example

Let us take an example where we need to set the following path to LD_LIBRARY_PATH:

/usr/local/lib

Then, the command will be:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

Alternatively, we can add the path in bashrc if you need this again when you start the session:

echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib' >> ~/.bashrc

With this article at OpenGenus, you have the complete idea of how to set the environment variable LD_LIBRARY_PATH.