動態鏈接庫的使用


針對二進制文件有用的命令

查看文件類型

file

查看二進制文件鏈接到哪些庫

ldd

查看二進制文件里面所包含的symbol,T表示加載,U表示undefined symbol

nm

讀二進制文件里面的信息

readelf -a smu.o

將二進制文件轉換為匯編

objdump -d sum.o

動態鏈接庫的生成

sum.c

#include <stdio.h>
#include <stdlib.h>

int sum(int x){
    int i, result=0;
    for(i=0; i<=x; i++){
        result+=i;
        }
    if(x > 100)
        exit(-1);
    return result;
};

void display(char* msg){
    printf("%s\n",msg);
}
  
int add(float a,float b){
    return a+b;
}

int sum_array(int array[], int num){
    int i =0, sum = 0; 
    for(i=0; i<num; ++i) 
        sum += array[i];
    return sum;
}

void modify_array(int array[], int num){
    int i =0, sum = 0; 
    for(i=0; i<num; ++i) 
        array[i] *= 10;
}

main.c

#include <stdio.h>
#include <stdlib.h>

int main(void){
    int x;
    printf("Input an integer:\n");
    scanf("%d", &x);
    printf("sum=%d\n", sum(x));
    return 0;
};

生成可執行文件

gcc -c main.c -o main.o
gcc -c sum.c -o sum.o
gcc sum.o main.o

將會生成main的可執行文件

file main     // ELF 64-bit LSB  executable
file sum.o    // ELF 64-bit LSB  relocatable

因為sum.c里面含有可復用的函數,所以想把sum.c編譯成為一個動態鏈接庫

gcc sum.o -shared -o sum.so

出現錯誤,提示

/usr/bin/ld: sum.o: relocation R_X86_64_PC32 against undefined symbol `exit@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status

這說明不是所有的.o文件都能編譯成為動態鏈接庫,需要在.o文件生成時加參數-fPIC

gcc -c sum.c -fPIC -o sum.o
gcc sum.o -o shared sum.so

一般,共享庫的編譯命令為(曾經的實驗)

動態鏈接庫
gcc -shared -fPIC -o libmyhello.so hello.o
gcc -o hello main.c -L. -lmyhello
靜態鏈接厙
ar rcs libxx.a xx.o 
g++ -o main main.cpp  -static -L.   -lxx

這時候再

g++ -o main main.c sum.so
./main 

有時會報錯

error while loading shared libraries: sum.so: cannot open shared object file: No such file or directory
ldd main
output:
sum.so => not found

這時候需要

export $LD_LIBRARY_PATH=pwd:$LD_LIBRARY_PATH

注意:-fPIC是生成.o時使用,-shared是用來生成動態鏈接庫的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM