g++ unable to link libgsl

Oliver picture Oliver · Sep 3, 2013 · Viewed 7.7k times · Source

I try to use the gsl library in one project, but I can't get the example program from the gsl website run properly. The source code and all commands are taken from the website: https://www.gnu.org/software/gsl/manual/html_node/Using-the-library.html#Using-the-library

The program is the following (test.cpp):

#include <stdio.h>
#include <gsl/gsl_sf_bessel.h>

int main (void) {
  double x = 5.0;
  double y = gsl_sf_bessel_J0 (x);
  printf ("J0(%g) = %.18e\n", x, y); 
  return 0;
}

Then I first compile without errors. But the linking fails:

$ g++ -Wall -I/usr/include/ -c test.cpp
$ g++ -L/usr/lib/ -lgsl -lgslcblas -lm test.o
test.o: In function `main':
test.cpp:(.text+0x1c): undefined reference to `gsl_sf_bessel_J0'
collect2: ld returned 1 exit status

But the libraries are available:

$ ll /usr/lib/libgsl*
lrwxrwxrwx 1 root root   16 Mar  2  2012 /usr/lib/libgsl.so.0 -> libgsl.so.0.16.0
lrwxrwxrwx 1 root root   16 Mar  2  2012 /usr/lib/libgsl.so -> libgsl.so.0.16.0
lrwxrwxrwx 1 root root   20 Mar  2  2012 /usr/lib/libgslcblas.so.0 -> libgslcblas.so.0.0.0
lrwxrwxrwx 1 root root   20 Mar  2  2012 /usr/lib/libgslcblas.so -> libgslcblas.so.0.0.0
-rw-r--r-- 1 root root 2.3M Mar  2  2012 /usr/lib/libgsl.so.0.16.0
-rw-r--r-- 1 root root 274K Mar  2  2012 /usr/lib/libgslcblas.so.0.0.0
-rw-r--r-- 1 root root 503K Mar  2  2012 /usr/lib/libgslcblas.a
-rw-r--r-- 1 root root 4.3M Mar  2  2012 /usr/lib/libgsl.a

As well as the header files:

$ whereis gsl
gsl: /usr/include/gsl /usr/share/man/man3/gsl.3.gz

I also tried downloading and installing the lib manually but there is no difference (this one is the Ubuntu package for 12.04 LTS).

/edit2:

Using nm it does not give any further hints:

$ nm /usr/lib/libgsl.a
[...]
bessel_J0.o:
00000000000004c0 T gsl_sf_bessel_J0
0000000000000000 T gsl_sf_bessel_J0_e
                 U gsl_sf_bessel_cos_pi4_e
[...]

Answer

Vivian Miranda picture Vivian Miranda · Sep 3, 2013

Easy fix:

You must link as follows

 g++ -L/usr/local/lib/ test.o -lgsl -lgslcblas -lm

You inverted the order while linking (first .o files, then the -l flags)

PS: I could reproduce your problem using your original

 g++ -L/usr/local/lib/ -lgsl -lgslcblas -lm test.o 

and I use gsl all the time without linking problem. I fixed by inverting the order as I said before.

PS2: enter image description hereSee picture