Search code examples
cgcclinkerwindows-subsystem-for-linuxlibsndfile

How to properly link libsndfile when compiling a standalone file using gcc


I'm using the libsndfile library for a signal processing project. I'm compiling c code using gcc on a WSL Ubuntu shell. I installed libsndfile-dev using sudo apt-get install libsndfile1-dev, as well as built the cloned libsndfile repository following its instructions on GitHub. As a test, I'm attempting to run https://github.com/libsndfile/libsndfile/blob/master/examples/make_sine.c outside the repository (it successfully generated the WAV file when ran within) by including the apt-get installed version.

When gcc make_sine.c is run, it generates the following errors:

make_sine.c:(.text+0x8d): undefined reference to `sf_open'
/usr/bin/ld: make_sine.c:(.text+0xed): undefined reference to `sin'
/usr/bin/ld: make_sine.c:(.text+0x15f): undefined reference to `sin'
/usr/bin/ld: make_sine.c:(.text+0x1a9): undefined reference to `sin'
/usr/bin/ld: make_sine.c:(.text+0x200): undefined reference to `sf_close'
/usr/bin/ld: make_sine.c:(.text+0x232): undefined reference to `sf_write_int'
/usr/bin/ld: make_sine.c:(.text+0x24f): undefined reference to `sf_strerror'
/usr/bin/ld: make_sine.c:(.text+0x263): undefined reference to `sf_close'
collect2: error: ld returned 1 exit status

I believe this is because the library is not properly linked in the gcc command. However, when I attempt to link the library, calling instead gcc make_sine.c -l sndfile, it generates the following errors:

/usr/bin/ld: /tmp/ccpubl3O.o: undefined reference to symbol 'sin@@GLIBC_2.2.5'
/usr/bin/ld: /lib/x86_64-linux-gnu/libm.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

Q8 of http://www.mega-nerd.com/libsndfile/FAQ.html specifies how to use libsndfile once it's installed. I've run all three commands, however, the final command simply generated the same output as gcc make_sine.c.

tl;dr: How do I properly compile make_sine.c outside of the libsndfile repository so that it generates a WAV file?


Solution

  • The problem is that you have to link the glibc math libraries in addition to libsdnfile. Running gcc make_sine.c -lm -lsndfile produces the correct output (sine.wav) upon execution of a.out. This works regardless of whether you use the apt-get version or run make install in a compiled cloned version of the libsndfile github.