1. 程式人生 > >linux下gcc編譯 .c檔案生成動態連結庫 .so檔案,並測試呼叫該連結庫

linux下gcc編譯 .c檔案生成動態連結庫 .so檔案,並測試呼叫該連結庫

簡單介紹:

linux中so檔案為共享庫,和windows下dll相似;

so可以共多個程序呼叫,不同程序呼叫同一個so檔案,所使用so檔案不同;

so原檔案不需要main函式;

例項,

1.通過mysqlTest.c中的函式mysql(),生成一個libmysql.so連結庫

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<mysql/mysql.h>

int mysql(void)
{
  char *sql;
  sql="SELECT * FROM test;";
  int res;//執行sql語句後的返回標誌
  MYSQL_RES *res_ptr;//指向查詢結果的指標
  MYSQL_FIELD *field;//欄位結構指標
  MYSQL_ROW result_row;//按行返回查詢資訊
  int row,column;//查詢返回的行數和列數
  MYSQL *conn;//一個數據庫連結指標
  int i,j;

  //初始化連線控制代碼
  conn = mysql_init(NULL);

  if(conn == NULL) { //如果返回NULL說明初始化失敗
    printf("mysql_init failed!\n");
    return EXIT_FAILURE;
  }

  //進行實際連線
  //引數 conn連線控制代碼,host mysql所在的主機或地址,user使用者名稱,passwd密碼,database_name資料庫名,後面的都是預設
  conn = mysql_real_connect(conn,"127.0.0.1","root","iotrobot","test",0,NULL,0);
  if (conn) {
    printf("Connection success!\n");
  } else {
    printf("Connection failed!\n");
  }
  mysql_query(conn,"set names gbk");//防止亂碼。設定和資料庫的編碼一致就不會亂碼

  res = mysql_query(conn,sql);//正確返回0
  if(res) {
    perror("my_query");
    mysql_close(conn);
    exit(0);
  } else{
    //把查詢結果給res_ptr
    res_ptr = mysql_store_result(conn);
    //如果結果不為空,則輸出
    if(res_ptr) {
      column = mysql_num_fields(res_ptr);
      row = mysql_num_rows(res_ptr);
      printf("查到行\n",row);
      //輸出結果的欄位名
      for(i = 0;field = mysql_fetch_field(res_ptr);i++) {
        printf("%10s",field->name);
      }
      puts("");
      //按行輸出結果
      for(i = 1;i < row+1;i++){
        result_row = mysql_fetch_row(res_ptr);
        for(j = 0;j< column;j++) {
          printf("%10s",result_row[j]);
        }
        puts("");
      }
    }

    //修改資料
    printf("update data!\n");
    mysql_query(conn,"update test set num3=num1+num2+num3 where id=0");
    printf("update data success!\n");
  }
  //退出前關閉連線
  mysql_close(conn);

  return 0;
}

編譯結果:生成libmysql.so

 mysqlTest.h檔案

    /* 
     * myqlTest.h 
     * 
     *  Created on: 2016年7月24日 
     *      Author: Andy_Cong 
     */  
      
    #ifndef MYSQLTEST_H_  
    #define MYSQLTEST_H_  
      
    int mysql(void);  
      
      
    #endif /* MYSQLTEST_H_ */  

測試函式main.c

#include<stdio.h>
#include<mysql/mysql.h>  
#include"mysqlTest.h"  
int main(void)  
{  
    printf("call max function results is: %d\n",mysql());  
    return 0;  
}  

使用命令  gcc -o  main main.c -L. -lmax -lmysqlclient        將main.c生成可執行程式main

再執行main程式即可

簡單解釋總結:

max.c裡面定義了函式max(),生成動態庫libmax.so

1.先編譯成.o

gcc -wall -g -fPIC  -c  max.c  -o  max.o   -lmysqlclient

 (max.c檔案編譯成max.o)

2. gcc -shared max.o -o libmax.so

3. 編寫一個max.h宣告max()函式,max.h就是庫檔案

4. 編寫一個main.c測試檔案,裡面包含庫檔案(標頭檔案)

max.h

main.c編譯成一個可執行的程式main

gcc -o main main.c -L. -lmax  -lmysqlclient

遇到問題:

1. 找不到 .so    

cannot open shared object file: No such file or directory

export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH

2. 程式中包含資料庫連線等,執行1 4命令時,加上-lmysqlclient