c++cgcclibmagic

GCC 4.8 fails while linking with libmagic


I am struggling with the issue while linking my code against libmagic:

test.c:(.text+0x16): undefined reference to `magic_open'
test.c:(.text+0x50): undefined reference to `magic_load'
test.c:(.text+0x60): undefined reference to `magic_error'
test.c:(.text+0x84): undefined reference to `magic_close'
test.c:(.text+0x9e): undefined reference to `magic_file'
test.c:(.text+0xba): undefined reference to `magic_close'
collect2: ld returned 1 exit status

However the issue appears only when gcc version > 4.4. To compile, I am using the the following command:

gcc -L/usr/lib/ -lmagic  test.c -o test

An example code that uses libmagic might be found here. I have checked and this issue appears as well. Obviously the libmagic and libmagic-dev are installed on my system (Ubuntu 14.04).

Is there any way of handling this issue different thant downgrading gcc version?


Solution

  • This is a FAQ, unrelated to your version of GCC.

    I don't think that your compilation succeeded with gcc-4.3

    Order of arguments to gcc matter a lot (see e.g. this); object files and libraries should go last (from the high-level to the low-level ones). Try with

     gcc  -Wall -g test.c -lmagic  -o mytest
    

    BTW, don't call your executable test (but e.g. mytest) since test is often a shell builtin.