Undefined reference on very simple program

拜拜、爱过 提交于 2019-12-19 03:24:26

问题


Once I installed Ubuntu 11.10, strange error appears. I want to use GD with my C program, so I installed package "libgd2-xpm-dev". Everything was installed - files gd.h and libgd.a are in "/usr/include" and in "/usr/lib". So, I've tried to compile simple program with 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'

Wait, what? Okay, let's check something.

# 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

And I don't know what shall I do. Is it an error in gcc or I do something wrong. On my previous os (Ubuntu 10.04) everything works well. Which file should I show for you?


回答1:


Change:

$ gcc -lgd gd.c

to:

$ gcc gd.c -lgd 

(Reason: link order matters !)

Oh, and add -Wall while you're at it - it pains me greatly every time I see people compiling with warnings disabled.

$ gcc -Wall gd.c -lgd 


来源:https://stackoverflow.com/questions/8415065/undefined-reference-on-very-simple-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!