[英]how to remove pthread undefined reference while building single thread library
我收到了pthread API 的未定義引用,但我不知道如何解決它們?
這是場景:
libA.a -- 這是第 3 方庫 [它包含許多依賴於 pthread 的 API]
libB.a——這是我自己的圖書館。 我使用了 3rd 方庫 [libA.a] 的幾個 API 並創建了我自己的庫。[我自己沒有在 libB.a 中使用任何 pthread API]
我將 libA.a + libB.a + (A + B) 的標頭提供給我的客戶端 exe。 -- 說 MAIN.exe
MAIN.cpp -- 將使用我的圖書館提供的 API。
當我嘗試運行 MAIN.exe 時,出現未定義的引用錯誤。
下面是源代碼:
libA.a:只包含Ah和A.cpp
class A { public: void dispA(); void printNumber(); };
#include "iostream"
#include "A.h"
#include<stdlib.h>
#include "pthread.h"
using namespace std;
void* printNum(void*)
{
sleep(1);
for(int i = 1; i<= 10; i++)
{
cout<<"i: "<<i<<endl;
}
pthread_exit(NULL);
return NULL;
}
void A::dispA()
{
cout<<"A::disp()"<<endl;
}
void A::printNumber()
{
pthread_t t1;
pthread_create(&t1, NULL, &printNum, NULL);
pthread_exit(NULL);
}
CD /練習/A
g++ -c A.cpp
ar -cvq libA.a *.o
libB.a:只包含 Bh 和 B.cpp
class B
{
public:
void funB();
void dispB();
};
#include "B.h"
#include "iostream"
#include "A.h"
using namespace std;
void B::funB()
{
cout<<"B::funB()"<<endl;
}
void B::dispB()
{
A a;
a.dispA();
a.printNumber();
}
創建 libB.a 的命令:
CD /練習/B
g++ -c B.cpp -I../A
ar -cvq libB.a *.o
#include "iostream"
#include "B.h"
using namespace std;
int main()
{
B b;
b.dispB();
b.funB();
return 0;
}
創建 main.exe 的命令:
cd /練習/主要
g++ -o noThread MAIN.cpp -I../A -I../B -L../A -L../B -lB -lA
我得到的錯誤:../ A::printNumber()': A.cpp:(.text+0x8c): undefined reference to
Ao): 在函數A::printNumber()': A.cpp:(.text+0x8c): undefined reference to
pthread_create' collect2: ld 返回 1 退出狀態
注意:我知道,如果我嘗試使用 -lrt 標志,它不會給出任何錯誤。 但問題是我的客戶端 [MAIN.cpp] 不能使用 -lrt 標志或 -lpthread 或任何與線程相關的庫。 因此,他建議我提供單線程庫。
那么,如何提供單線程庫????
libA.a 是第三方,我無法更改其代碼。 libB.a 是我自己的庫 [我必須使用 libA.a 中的 API]
是否有任何特定的標志可以用來使 main.cpp 正常運行?
另一個疑問:
為什么 Main.cpp 給我錯誤,即使客戶端只調用線程獨立函數:
int main()
{
B b;
//b.dispB(); <== commented thread dependent function
b.funB(); <== this doesn't depend on pthread. but still main.cpp is failing. Don't know WHY !!
return 0;
}
如果您確定沒有從您的庫使用的代碼路徑中調用實際的pthread
代碼,那么您可以嘗試制作ptherad
調用的虛擬版本,如下所示:
DummyPThreads.c (注意 c 不是 c++)
int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void *), void*)
{
return 0;
}
void pthread_exit(void*)
{
}
// etc...
編譯:
gcc -c -o DummyPThreads.o DummyPThreads.c
添加到您的應用程序:
g++ -o noThread MAIN.cpp -I../A -I../B DummyPThreads.o -L../A -L../B -lB -lA
這是不可能的。 由於庫之一依賴於 pthread,您需要將庫鏈接到最終的可執行文件。
唯一的選擇是從 libA.a 中提取您真正需要的文件,並且它們不依賴於 pthread。 但是相當艱巨的任務,很可能是不可能的,因為通常存在交叉依賴關系,最后但並非最不重要的是,如果庫發生變化,則非常脆弱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.