ºìÁªLinuxÃÅ»§
Linux°ïÖú

Linux ¿âÉú³ÉºÍʹÓÃ

·¢²¼Ê±¼ä:2008-04-24 15:34:41À´Ô´:ºìÁª×÷Õß:Syah
¾²Ì¬¿âµÄ´´½¨ºÍʹÓãº
1¡¢Éú³É¾²Ì¬¿â £º¿âÃû libmylib.a
ar rcs libmylib.a mylib.o
2¡¢½«¾²Ì¬¿âcopyµ½ /usr/lib/ »ò/lib/ Ŀ¼ÏÂ
cp libmylib.a /usr/lib/
3¡¢¾²Ì¬¿âµÄʹÓÃ
±ÈÈç²âÊÔÎļþΪtest.c
gcc -0 test test.c -lmylib
-lΪѡÏ mylibΪ¿âÃû¡£mylibΪlibmylibµÄÖм䲿·Ö£¬LinuxÏÂÔ¼¶¨ËùÓпⶼÒÔǰ׺lib¿ªÊ¼
¾²Ì¬¿âÒÔ.a½á⣬¶¯Ì¬¿âÒÔ.so½áβ¡£ÔÙ±àÒë³Ìʽʱ£¬ÎÞÐè´øÉÏǰ׺ºÍºó׺¡£
×¢Ò⣺¾²Ì¬¿âµÄÃüÃûÐèÒªÒÔ"lib"¿ªÍ·£¬·ñÕßÁ¬½ÓÊDZàÒëÆ÷ÎÞ·¨ÕÒµ½¿â
¶¯Ì¬¿âµÄ´´½¨ºÍʹÓãº
Ò»¡¢ÏÂÃæÃüÁî°Ñmylib.c³ÌÐò´´½¨³ÉÁËÒ»¸ö¶¯Ì¬¿â
1¡¢gcc -fPIC -o mylib.o -c mylib.c
2¡¢gcc -shared -o libttt.so mylib.o
Ò²¿ÉÒÔÖ±½ÓʹÓÃÒ»ÌõÃüÁî
gcc -fPIC -shared -o libttt.so mylib.c

¶þ¡¢LinuxÓÐÁ½ÖÖ·½Ê½µ÷Óö¯Ì¬¿âÁ¬½ÓÖеĺ¯Êý
1¡¢gcc -o test test.c ./libttt.so
2¡¢
cp libttt.so /usr/lib/libttt.so
gcc -o test test.c /usr/lib/libttt.so
×¢Ò⣺ÒýÓö¯Ì¬¿âʱ£¬±ØÐ뺬Óз¾¶£¬Èç¹ûÖ»ÊÇʹÓÃlibttt.so,Ôò±ØÐëÈ·±£Õâ¸ö¿âËùÔÚĿ¼°üÀ¨ÔÙPATH »·¾³±äÁ¿ÖÐ

ϵͳº¯ÊýʹÓö¯Ì¬¿â
1¡¢void *dlopen(const char *filename, int flag)
ÓÃÓÚ´ò¿ªÖ¸¶¨Ãû×ֵĶ¯Ì¬Á´½Ó¿â£¬²¢·µ»ØÒ»¸ö¾ä±ú
flag:RTLD_LAZY, RTLD_NEW, RTLD_GLOBAL
RTLD_LAZY:ÔÚdlopen()·µ»ØÇ°£¬¶ÔÓÚ¶¯Ì¬¿âÖдæÔÚµÄ䶨ÒåµÄ±äÁ¿(ÈçÍⲿ±äextern,Ò²¿ÉÒÔÊǺ¯Êý)
²»Ö´ÐнâÎö£¬Ò²¾ÍÊDz»½âÎöÕâ¸ö±äÁ¿µÄµØÖ·
RTLD_NEW£ºÓëRTLD_LAZY ²»Í¬£¬ÔÚdlopen()·µ»ØÇ°£¬½âÎö´¦Ã¿¸ö䶨ÒåµÄ±äÁ¿µÄµØÖ·£¬Èç¹û½âÎö²»³öÀ´
£¬dlopen»á·µ»ØNULL£¬´íλΪ"undefined symbol:xxx..."
RTLD_GLOBAL:ÊÇ¿âÖб»½âÎö³öÀ´µÄ±äÁ¿ÔÚËæºóµÄÆäËüÁ´½Ó¿âÖÐÒ²¿ÉÒÔʹÓ㬼´È«¾ÖÓÐЧ¡£
2¡¢void *dlsym(void *handle, char *symbol)
¸ù¾Ý¶¯Ì¬Á´½Ó¿âµÄ¾ä±úÓ뺯ÊýÃû£¬·µ»Øº¯ÊýÃû¶ÔÓ¦µÄº¯ÊýµÄµØÖ·¡£
3¡¢int dlclose(void *handle)
¹Ø±Õ¶¯Ì¬Á´½Ó¿â£¬handleÊǵ÷ÓÃdlopenº¯Êý¿âµÄ¾ä±ú
4¡¢const char *dlerror(void)
¶¯Ì¬¿âÁ´½Ó¿âÖ´ÐÐʧ°Üʱ£¬dlerror·µ»Ø´íÎóÐÅÏ¢£¬ÈôÖ´Ðгɹ¦£¬Ôò·µ»ØNULL

Àý×Ó£ºmain.c
int main(void)
{
void *handle;
char *error;
void (*welcome)();

if ((handle = dlopen("./libttt.so", RTLD_LAZY)) == NULL)
{
printf("dlopen error\n");
return -1;
}

welcome = dlsym(handle, "welcome");
if ((error = dlerror()) != NULL)
{
printf("dlsym error\n");
return -1;
}
welcome();
dlclose(handle);

return 0;
}

gcc -ldl -o main main.c
-ldl Ö¸Ã÷dlopenº¯ÊýËùÔڵĿ⡣
×¢Ò⣺dlopen("./libttt.so", RTLD_LAZY),µÄĿ¼ÊÇÔÚµ±Ç°Ä¿Â¼Ï£¬Èç¹û²»ÔÚµ±Ç°Ä¿Â¼Ï£¬³ÌÐòÔËÐдíÎó

¹²Ïí¿â½øÐиüлò°²×°Ð¿âºó£¬±ØÐëÔËÐÐldconfigÃüÁî¸üÐÂ/etc/ld.confÎļþÖÐÏàÓ¦µÄÏî
Èç¹ûʹÓÃRPM½øÐа²×°£¬Ò»°ã»á×Ô¶¯½øÐиüУ¬²»¹ýÒ²²»Äܱ£Ö¤ÕâÒ»µã¡£

ʹÓÃÊýѧ¿âʱ¼ÓÉÏ -lm
gcc -lm

¿â¹¤¾ßʹÓãº
1. ldd ¹¤¾ß
ldd ÓÃÀ´ÏÔʾִÐÐÎļþÐèÒªÄÄЩ¹²Ïí¿â, ¹²Ïí¿â×°ÔعÜÀíÆ÷ÔÚÄÄÀïÕÒµ½ÁËÐèÒªµÄ¹²Ïí¿â.
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 2 ÌõÆÀÂÛ

  1. exterminator ÓÚ 2008-04-24 18:19:40·¢±í:

    ÕâÊÇÓÃÀ´×öʲôµÄ°¡

  2. jlqi ÓÚ 2008-04-24 17:57:24·¢±í:

    ѧϰÁË£¡£¡ÎÒÊÇÐÂÊÖ£¬¸Õ½Ó´¥linux¡£