error LNK2019: 無法解析的外部符號 "void * __cdecl put_buf(void *)" (?put_buf@@YAPAXPAX@Z),
該符號在函數 _main 中被引用
error LNK2019: 無法解析的外部符號 "void * __cdecl get_buf(void *)" (?get_buf@@YAPAXPAX@Z)...
函數聲明與定義參數列表不一致:
C++ 編譯器按**函數簽名(名稱+參數類型)**匹配符號,參數不匹配導致鏈接器找不到定義。
// 1. 定義在 main 之前,無需前置聲明
void *put_buf(void *arg) { // 保留參數以符合 pthread_create 要求
// ...
}
void *get_buf(void *arg) {
// ...
}
int main() {
// 直接調用,無需聲明
pthread_create(&t1, NULL, put_buf, NULL);
// ...
}
// 前置聲明:必須與定義完全一致
void *put_buf(void *arg);
void *get_buf(void *arg);
int main() {
// ...
}
// 定義
void *put_buf(void *arg) { ... }
void *get_buf(void *arg) { ... }
原代碼邏輯有死鎖風險(`put_buf` 中 `pthread_cond_wait` 前未持有鎖,`get_buf` 中 `signal` 後未解鎖)。標準模式:
// 生產者
pthread_mutex_lock(&lock);
while (buffer_full) pthread_cond_wait(&empty, &lock);
// 生產數據
pthread_cond_signal(&full);
pthread_mutex_unlock(&lock);
// 消費者
pthread_mutex_lock(&lock);
while (buffer_empty) pthread_cond_wait(&full, &lock);
// 消費數據
pthread_cond_signal(&empty);
pthread_mutex_unlock(&lock);
LNK2019 核心是**聲明定義不匹配**。Windows 使用 pthread 需注意庫配置、函數簽名標準化、同步原語正確使用。建議新項目優先考慮 C++11 `std::thread`/`std::mutex`/`std::condition_variable`,跨平台無需第三方庫。