如何在构建单线程库时删除 pthread 未定义引用

how to remove pthread undefined reference while building single thread library

我得到 未定义的引用 pthread API 的,我不知道如何解决它们?

场景如下:

libA.a -- 这是第 3 方库 [它包含很多 API 依赖于 pthread]

libB.a -- 这是我自己的图书馆。我正在使用少数 API 的第 3 方库 [libA.a] 并创建了我自己的库。[我自己没有在 libB.a] 中使用任何 pthread API

我将 (A + B) 的 libA.a + libB.a + headers 提供给我的客户端 exe。 -- 说 MAIN.exe

MAIN.cpp -- 将使用我的图书馆提供的 API。

当我尝试 运行 MAIN.exe 时,出现未定义的引用错误。

下面是源码:

libA.a: 只包含A.h和A.cpp

A.h

class A { public: void dispA(); void printNumber(); };

A.cpp:

#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);
}

创建命令 libA.a:

cd /practise/A

g++ -c A.cpp

ar -cvq libA.a *.o

libB.a: 只包含B.h和B.cpp

B.h:

class B
{
public:
    void funB();
    void dispB();
};

B.cpp:

#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 /practise/B

g++ -c B.cpp -I../A

ar -cvq libB.a *.o

Main.cpp:

#include "iostream"
#include "B.h"
using namespace std;

int main()
{
    B b;
    b.dispB();
    b.funB(); 
    return 0;
}

创建命令main.exe:

cd /practise/MAIN

g++ -o noThread MAIN.cpp -I../A -I../B -L../A -L../B -lB -lA

我得到的错误: ../A/libA.a(A.o): 在函数中 A::printNumber()': A.cpp:(.text+0x8c): undefined reference topthread_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,因此您需要 link 将库添加到最终的可执行文件中。

唯一的选择是从 libA.a 中提取您真正需要的文件,并且它们不依赖于 pthread。但这是一项非常艰巨的任务,很可能是不可能的,因为通常存在交叉依赖关系,最后但并非最不重要的一点是,如果库发生变化,则非常脆弱。

如果您确定没有从您的库使用的代码路径调用实际的 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