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 介面函式。C++ 編譯器對函數名進行 **Name Mangling** (如 _Z23SetPduPowerConsumptionCntij),C 編譯器期望純符號名 SetPduPowerConsumptionCnt。解決:在 C++ 實作檔加上 extern "C"。
// 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++ **區分大小寫**,連結器視為兩個不同符號。
// 錯誤:小寫 s
extern "C" int setPduPowerConsumptionCnt(int index, unsigned int val);
extern "C" int setPduPowerConsumptionTot(int index, unsigned int val);
// 錯誤:大寫 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) { ... }
extern "C"。#ifdef __cplusplus extern "C" { #endif,確保 C/C++ 皆可包含。Makefile 正確編譯 .cpp (g++) 與 .c (gcc) 並連結同一執行檔。make clean; make 確無殘留舊物件檔。# 查看物件檔符號表
arm-linux-nm modelc.o | grep -i setpdu
# 預期輸出 (小寫、無修飾)
00000000 T setPduPowerConsumptionCnt
00000000 T setPduPowerConsumptionTot
extern "C" 也適用於 C++ 呼叫 C 函式庫 (如 Lua、SQLite、FFmpeg)。std::string_view、std::span 等現代介面設計可減少 C 風格介面需求。nm/objdump 定期檢查符號表一致性。「大小寫不一致」是跨語言連結最隱蔽的坑,**統一命名規範 (如 snake_case) + 編譯器警告開啟 (-Wall -Wextra)** 可有效預防。