萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 交叉編譯 undefined reference to SetPduPowerConsumptionCnt 錯誤排查:extern "C" 與大小寫不一致

ARM 交叉編譯環境 (arm-linux-g++) 中,C 語言檔案呼叫 C++ 模型函數時出現 undefined reference to `SetPduPowerConsumptionCnt'。根因有二:缺少 extern "C" 導致名稱修飾不匹配、頭文件與實作檔函數名大小寫不一致。

錯誤現場

sensor-att7053.c:83: undefined reference to `SetPduPowerConsumptionCnt'
sensor-att7053.c:92: undefined reference to `SetPduPowerConsumptionTot'
collect2: ld returned 1 exit status

專案架構

  • model.cpp:C++ 核心模型類別。
  • modelc.h / modelc.cpp:C 介面層,供 .c 檔呼叫。
  • sensor-att7053.c:C 語言感測器驅動,呼叫 C 介面函式。

根因一:缺少 extern "C"

C++ 編譯器對函數名進行 **Name Mangling** (如 _Z23SetPduPowerConsumptionCntij),C 編譯器期望純符號名 SetPduPowerConsumptionCnt。解決:在 C++ 實作檔加上 extern "C"。

修正 modelc.cpp

// modelc.cpp
#include "modelc.h"
#include "model.h"

extern "C" int setPduPowerConsumptionCnt(int index, unsigned int val) {
  if (index > 8 || index < 1) {
    printf("Error: Index must be 1~8\n");
    return -1;
  }
  model->Channels()[index-1].TheEnergyPort().SetPowerConsumptionCount(val);
  return 0;
}

extern "C" int setPduPowerConsumptionTot(int index, unsigned int val) {
  // ... 類似實作
  return 0;
}

根因二:頭文件與實作大小寫不一致

發現頭文件宣告小寫 setPduPowerConsumptionCnt,實作卻寫大寫 SetPduPowerConsumptionCnt。C/C++ **區分大小寫**,連結器視為兩個不同符號。

modelc.h (修正前)

// 錯誤:小寫 s
extern "C" int setPduPowerConsumptionCnt(int index, unsigned int val);
extern "C" int setPduPowerConsumptionTot(int index, unsigned int val);

modelc.cpp (修正前)

// 錯誤:大寫 S
extern "C" int SetPduPowerConsumptionCnt(int index, unsigned int val) { ... }
extern "C" int SetPduPowerConsumptionTot(int index, unsigned int val) { ... }

修正後一致版本

// modelc.h
#ifdef __cplusplus
extern "C" {
#endif
int setPduPowerConsumptionCnt(int index, unsigned int val);
int setPduPowerConsumptionTot(int index, unsigned int val);
#ifdef __cplusplus
}
#endif

// modelc.cpp
#include "modelc.h"
#include "model.h"

extern "C" int setPduPowerConsumptionCnt(int index, unsigned int val) { ... }
extern "C" int setPduPowerConsumptionTot(int index, unsigned int val) { ... }

排查檢查清單

  1. ✅ C++ 實作檔函數定義前有 extern "C"。
  2. ✅ 頭文件宣告包裹在 #ifdef __cplusplus extern "C" { #endif,確保 C/C++ 皆可包含。
  3. ✅ 宣告與定義**函數名大小寫完全一致** (含參數型別)。
  4. ✅ Makefile 正確編譯 .cpp (g++) 與 .c (gcc) 並連結同一執行檔。
  5. ✅ 執行 make clean; make 確無殘留舊物件檔。

編譯器檢查技巧

# 查看物件檔符號表
arm-linux-nm modelc.o | grep -i setpdu

# 預期輸出 (小寫、無修飾)
00000000 T setPduPowerConsumptionCnt
00000000 T setPduPowerConsumptionTot

延伸學習

  • extern "C" 也適用於 C++ 呼叫 C 函式庫 (如 Lua、SQLite、FFmpeg)。
  • C++17 std::string_view、std::span 等現代介面設計可減少 C 風格介面需求。
  • 大型專案建議用 nm/objdump 定期檢查符號表一致性。

「大小寫不一致」是跨語言連結最隱蔽的坑,**統一命名規範 (如 snake_case) + 編譯器警告開啟 (-Wall -Wextra)** 可有效預防。

copyright © 萬盛學電腦網 all rights reserved