Search code examples
cfreeimage

How do I link to FreeImage?


I am using Kubuntu 14.04, and installed the FreeImage library with

sudo apt-get install libfreeimage-dev

As far as I can tell, it is correctly installed, with FreeImage.h in /usr/include and libfreeimage.a in /usr/lib. However, this trivial C program

#include <FreeImage.h>

int main(int argc, char **argv) {

  FreeImage_Initialise(FALSE);
  FreeImage_DeInitialise();
  return 0;

}

fails to compile. Running

gcc -lfreeimage fitest.c -o fitest

outputs

/tmp/ccFbb0HQ.o: In function `main':
fitest.c:(.text+0x15): undefined reference to `FreeImage_Initialise'
fitest.c:(.text+0x1a): undefined reference to `FreeImage_DeInitialise'
collect2: error: ld returned 1 exit status

What am I doing wrong?


Solution

  • This wouldn't normally be the case with shared libraries but only static ones, but I'm going to give it a shot anyway since it matches your symptoms, and you also mention libfreeimage.a instead of libfreeimage.so, indicating that you're trying to use the static library.

    When linking against static libraries, you need to give the library arguments after the explcit source/object arguments to the compiler, because the compiler will only process yet unresolved symbols from the library:

    gcc -o fitest fitest.c -lfreeimage
    

    If you give a static library argument before any source/object arguments, then, no symbols will yet be unresolved, nothing will be picked from the library, and the symbols will instead be seen as unresolved at the end.