对静态队列的未定义引用 [英] Undefined reference to static queue

查看:161
本文介绍了对静态队列的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C ++ pthreads。我想做的是使用一个线程捕获UDP数据包并将其放入队列,另一个线程处理它们并发送它们。我的问题是,我如何在一个单独的线程中push / pop一个容器中的元素?

I'm new with C++ pthreads. What I'm trying to do is use one thread to catch UDP packets and put it into a queue, and another one to process them and send them after. My question is, how can I push/pop elements into/from a container in a separate thread?

这里有一个例子:

#include <queue>
#include <iostream>
#include <pthread.h>
#include <signal.h>

class A{
public:
    A(){
        pthread_create(&thread, NULL, &A::pushQueue, NULL);

        pthread_join(thread, NULL);
    }
    virtual ~A(){
        pthread_kill(thread, 0);
    }

private:
    static void* pushQueue(void* context){
        for(int i = 0; i < 10; i++){
            bufferInbound.push(i);
            std::cout << i << " pushed!" << std::endl;
        }
    }

    static std::queue<int> bufferInbound;
    pthread_t thread;
};

int main(){
    A* a = new A();

    return 0;
}

当我编译时,它给我以下结果:

When I compile, it gives me the following result:

U53R@Foo:~/$ make
g++ -g -lpthread main.cpp -c
g++ -g -lpthread main.o -o this
main.o: In function `A::pushQueue(void*)':
/home/U53R/main.cpp:20: undefined reference to `A::bufferInbound'
collect2: ld returned 1 exit status
make: *** [make] Error 1

感谢您的帮助。

推荐答案

您需要初始化静态成员,添加 std :: queue< int> A :: bufferInbound; 后面的类或将其移动到你的函数内。

you need to initialize the static member, add std::queue<int> A::bufferInbound; after the class or move it inside your function.

这篇关于对静态队列的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆