ÔÚLinuxÉÏÓÃC´´½¨¹²Ïí¿âso
1¡¢´´½¨math1.c£¬ÔÚÃüÁîÐÐÖÐÊäÈ룺nano math1. c
int add(int x, int y)
{
return x+y;
}
2¡¢±àÒëÉú³É¹²Ïí¿âlibmath1.so
gcc -fPIC -shared -olibmath1.so math1.c
3¡¢´´½¨²âÊÔ³ÌÐòtestmath.c£¬ÔÚÃüÁîÐÐÖÐÊäÈ룺nano testmath. c
#include
int main()
{
int x=10, y=18;
int sum = add(x, y);
printf("%d+%d=%d\n", x, y, sum);
return 0;
}
4¡¢±àÒëÉú³É²âÊÔ³ÌÐòtestmath
gcc -otestmath -lmath1 testmath.c -L=./
5¡¢ÔËÐвâÊÔ³ÌÐò£¬ÔÚÃüÁîÐÐÖÐÊäÈ룺./testmath
³öÏÖÕÒ²»µ½¹²Ïí¿âµÄ´íÎó£º
./testmath: error while loading shared libraries: libmath1.so: cannot open shared object file: No such file or directory
6¡¢¿½±´libmath1.soµ½LinuxϵͳĬÈϵĹ²Ïí¿â¼ÓÔØ·¾¶(/lib»ò/usr/lib)
ÔÚÃüÁîÐÐÖÐÊäÈ룺sudo cp libmath1.so /usr/lib/
7¡¢ÖØÐÂÔËÐвâÊÔ³ÌÐòtestmath
½á¹û£º10+18=28
¹ØÓÚgccµÄ±àÒë²ÎÊý£º
-fPIC Éú³ÉÓëλÖÃÎ޹صĴúÂ룬ÕâÑù¿â¾Í¿ÉÒÔÔÚÈκÎλÖñ»Á¬½ÓºÍ×°ÔØ
-shared ´ú±í¹²Ïí¿â
-o Á´½ÓÉú³ÉÖ¸¶¨Ãû×ֵĿâ»ò³ÌÐò
-l Ö¸¶¨ÒªÁ´½ÓµÄ¹²Ïí¿â
-L Ö¸¶¨¹²Ïí¿âËùÔÚ·¾¶