日期:2014-05-16  浏览次数:20712 次

linux下调用链接库问题
目录结构如下:
ctest
|--   hello.c
|--   hello.h
`--   lib
        |--   head.h
        |--   libtest.so
        |--   package1.c
        `--   package2.c

//******package1.c*********
#include   "head.h "

void   fun1()
{
                printf( "in   fun1,   package1......\n ");
}

void   fun2()
{
                printf( "in   fun2,   package1......\n ");
}

//*******package2.c**********************
#include   "head.h "

void   fun3()
{
                printf( "in   fun3,   package2......\n ");
}

void   fun4()
{
                printf( "in   fun4,   package2......\n ");
}

//********head.h********
#include   <stdio.h>
void   fun1();
void   fun2();
void   fun3();
void   fun4();

//***********hello.c*************
#include   "hello.h "
#include   "head.h "
int   main(int   argv,   char   **   argc)
{
                printf( "begin......\n ");
                func1();
                printf( "end......\n ");
                return   1;
}

//***************hello.h***************
#include   <stdio.h>

[root@localhost   lib]$   gcc   package1.c   package2.c   -fPIC   -shared   -o   libtest.so
 
[root@localhost   lib]$   cd   ..

[root@localhost   ctest]$   gcc   hello.c   -I   ./lib   -L   ./lib   -ltest   -o   hello
/tmp/ccuTyqmn.o:   In   function   `main ':
hello.c:(.text+0x1e):   undefined   reference   to   `func1 '
collect2:   ld   返回   1

报错说找不到func1的定义,但是我已经将func1,func2,func3,func4打到了libtest.so包中,并且将那个包加进来了,为什么还找不到阿?

------解决方案--------------------
原因1. gcc hello.c -I ./lib -L ./lib -ltest -o hello 不对。-L ./lib中间没有空格,
像这样:gcc hello.c -I./lib -L./lib -ltest -o hello,不然找不到libtest.so

原因2. main里的函数调用func1();名字不对,在包里的函数明明是fun1,fun2,fun3,fun4

------解决方案--------------------
有没空格无关.
主要是main()内函数名不对.