【问题标题】:Undefined reference for boost::mutex in struct结构中 boost::mutex 的未定义引用
【发布时间】:2016-11-11 22:49:08
【问题描述】:

我想为我的结构 Cell 的函数 add 使用 boost::mutex。这是我在 Detector.h 中的结构的定义

class Detector {

private:
    struct  Cell{
        static boost::mutex mutex_;
        double energy;
        double sqrt_energy;
        int histories;

        inline Cell(): energy(0.f), sqrt_energy(0.f), histories(0.f) {
            boost::mutex mutex_;  //I tried with and without this line
        };  

        inline void add(double new_energy) {
            mutex_.lock();
            energy += new_energy;
            sqrt_energy += new_energy*new_energy;
            ++histories;
            mutex_.unlock();
        };
    };

    typedef std::vector<Cell> CellVector;
    CellVector EnergyPrimary;

}

我在 Detector.cpp 中的 Cell 向量上使用我的函数 add

Dectetor::Detector() : {
  nVoxelX=1024;
  nVoxelY=1024;
  size=nVoxelX*nVoxelY;
  EnergyPrimary=CellVector(size);
}

void Detector::Score(int cellID, double new_energy) {
  EnergyPrimary[cellID].add(new_energy);
}

当我尝试编译它时,mutex_.lock() 和 mutex_.unlock() 出现未定义的引用错误。但是为什么在我用类似的函数重载运算符 += 之前(以及当我调用 EnergyPrimary[cellID].energy += new_energy;)之前它仍然有效?

inline bool operator+= (double new_energy) {
    mutex_.lock();
    energy += new_energy;
    mutex_.unlock();
    return false;
};

【问题讨论】:

  • 是否包含头文件?你的编译器知道在哪里可以找到 boost?
  • 你的 'mutex_' 是静态的,但我看不出你在哪里定义它。您真的希望所有单元和所有检测器只需要一个互斥锁吗?
  • Jepessen :是的,我包含了它,是的,我的编译器发现了 boost。我的错误是对 `Detector::Cell::mutex_' 的未定义引用
  • qPCR4vir :我试图定义它(我用这一行编辑我的帖子),但它仍然不起作用。我想要每个单元格一个互斥锁。

标签: c++ boost-mutex


【解决方案1】:

您已将mutex_ 定义为类的静态成员,这意味着它不是每个实例的成员。因此,您不能在构造函数中进行初始化。相反,它必须在源文件中初始化,在您的情况下很可能是 Detector.cpp

初始化代码应该是:

boost::mutex Detector::Cell::mutex_;

如果您不希望它成为静态成员(您希望每个单元有一个互斥锁),请删除 static 限定符。

【讨论】:

  • 谢谢,我将静态互斥锁更改为指向互斥锁的指针,我在我的内联 Cell() 函数中初始化了它,它似乎可以工作。
猜你喜欢
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
  • 2012-11-08
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多