关于非常简单的程序的未定义参考

时间:2011-12-07 12:08:03

标签: gcc linker linker-errors undefined-reference

安装Ubuntu 11.10后,出现奇怪的错误。我想用我的C程序使用GD,所以我安装了包“libgd2-xpm-dev”。一切都已安装 - 文件gd.h和libgd.a位于“/ usr / include”和“/ usr / lib”中。所以,我试图用GD编译简单的程序。

#include <stdio.h>
#include <gd.h>

int main()
{
        gdImagePtr im, im_clear;
        int black, white;
        FILE *out1;

        im = gdImageCreate(100, 100);
        im_clear = gdImageCreate(100, 100);

        white = gdImageColorAllocate(im, 255, 255, 255);
        black = gdImageColorAllocate(im, 0, 0, 0);
        return 0;
}

$ gcc -lgd gd.c
/tmp/cc6LReuX.o: In function `main':
gd2.c:(.text+0x19): undefined reference to `gdImageCreate'
gd2.c:(.text+0x31): undefined reference to `gdImageCreate'
gd2.c:(.text+0x59): undefined reference to `gdImageColorAllocate'
gd2.c:(.text+0x81): undefined reference to `gdImageColorAllocate'
等等,什么?好的,我们来检查一下。

# Let's sure the lib was found.
$ gcc -lgd_something gd.c
/usr/bin/ld: cannot find -lgd_something

# Lets sure we made no mistake with the symbol's name
$ nm /usr/lib/libgd.a
...
00000dc0 T gdImageColorAllocate
...
000003b0 T gdImageCreate

# So, everything should be ok
$ gcc -lgd gd.c
/tmp/cc6LReuX.o: In function `main':
gd2.c:(.text+0x19): undefined reference to `gdImageCreate'
gd2.c:(.text+0x31): undefined reference to `gdImageCreate'
gd2.c:(.text+0x59): undefined reference to `gdImageColorAllocate'
gd2.c:(.text+0x81): undefined reference to `gdImageColorAllocate'

$ echo $LD_LIBRARY_PATH
# Nothing

我不知道该怎么办。这是gcc中的错误还是我做错了什么。在我以前的操作系统(Ubuntu 10.04)上一切正常。 我应该为您展示哪个文件?

1 个答案:

答案 0 :(得分:5)

变化:

$ gcc -lgd gd.c

为:

$ gcc gd.c -lgd 

(原因:link order matters!)

哦,并且当你在它的时候添加-Wall - 每当我看到人们编译并禁用警告时,我就会非常痛苦。

$ gcc -Wall gd.c -lgd