GCC 4.8 在与 libmagic 链接时失败

GCC 4.8 fails while linking with libmagic

我在将我的代码与 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

不过只有当gcc版本> 4.4时才会出现这个问题。要编译,我使用以下命令:

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

可能会找到使用 libmagic 的示例代码 here。我已经检查过,这个问题也出现了。显然我的系统上安装了 libmagic 和 libmagic-dev (Ubuntu 14.04).

除了降级 gcc 版本之外,还有其他处理此问题的方法吗?

这是一个常见问题解答,与您的 GCC 版本无关。

我不认为你的编译成功 gcc-4.3

gcc 的参数顺序很重要(参见 this);目标文件和库应该放在最后(从高级到低级)。试试

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

顺便说一句,不要调用您的可执行文件 test(但例如 mytest),因为 test 通常是 shell 内置的。