首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

為 libnfc 函式庫新增自訂標頭檔的完整實踐記錄

     編輯:關於C語言

libnfc 增加自訂函式 MycharToInt 的曲折過程

背景與目標

需要在 libnfc 函式庫中新增一個十六進位字串轉整數的函式 MycharToInt(char *pch),並使現有的 log.h 模組能夠呼叫。

第一嘗試:獨立標頭/原始檔(失敗)

MycharToInt.h

#ifndef __MYCHARTOINT_H__
#define __MYCHARTOINT_H__
int MycharToInt(char *pch);
#endif

MycharToInt.c

#include "MycharToInt.h"
int MycharToInt(char *pch) {
    int result = 0, ch1 = pch[0], ch2 = pch[1];
    int shiwei = 0, gewei = 0;
    // 十六進位字元轉數值邏輯(0-9, A-F, a-f)
    if (ch1 >= '0' && ch1 <= '9') shiwei = ch1 - '0';
    else if (ch1 >= 'A' && ch1 <= 'F') shiwei = ch1 - 'A' + 10;
    else if (ch1 >= 'a' && ch1 <= 'f') shiwei = ch1 - 'a' + 10;
    if (ch2 >= '0' && ch2 <= '9') gewei = ch2 - '0';
    else if (ch2 >= 'A' && ch2 <= 'F') gewei = ch2 - 'A' + 10;
    else if (ch2 >= 'a' && ch2 <= 'f') gewei = ch2 - 'a' + 10;
    result = shiwei * 16 + gewei;
    return result;
}

建置過程

cd libnfc
sudo ./configure --with-drivers=pn532_uart --enable-debug
sudo make clean all
sudo make install

編譯通過,但執行 libllcp/examples/npp-server 時報錯:no symbol of MycharToInt。原因:動態連結器在執行期找不到該符號,獨立編譯的物件未被正確連結進 libnfc 共享庫。

最終解決方案:整合進 libnfc 內部建置體系

libnfc 內部模組 log.h 包含 nfc-internal.h,將函式宣告放入內部標頭,實作放入內部原始檔,隨庫一起編譯連結。

修改 nfc-internal.h

// 在現有宣告區塊新增
int MycharToInt(char *pch);

修改 nfc-internal.c


// 在檔案中實作函式
int MycharToInt(char *pch) {
    // 同上實作邏輯
    ...
}

重新建置

sudo make clean all && sudo make install

此後 log.h 及任何包含 nfc-internal.h 的模組均可直接呼叫 MycharToInt(),符號正確匯出至共享庫,執行期解析成功。

關鍵教訓

  1. 開源庫擴充函式需納入其建置系統(Makefile.am/CMakeLists.txt),確保符號編入共享庫。
  2. 內部標頭(如 nfc-internal.h)通常為庫內部模組共享,適合放置新增 API 宣告。
  3. 獨立編譯 .c/.h 並手動連結極易導致符號可見性、相依順序、安裝路徑等問題。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved