【问题标题】:Linking error in dereferencing static variable取消引用静态变量时的链接错误
【发布时间】:2023-04-05 12:26:01
【问题描述】:

(我没有找到任何类似的问题......所以,我希望你能帮助我)

在我正在开发的 C++ 程序中,我有一个模拟线程的类。我在这里称它为“测试”。在其中,我有一个静态映射(std::map,来自 STL),其中存储了一些信号量(因为我需要所有线程都可以访问相同的信号量)。 (我认为不值得解释为什么我使用map,而不是vector,但我相信这应该不是问题)

为了“获取”这个静态变量,我创建了一个getMutexHash() 函数,它返回一个指向静态map 的指针。但是,由于某种原因,在编译后,我在尝试返回 this pointer 时遇到了链接器错误。

下面的代码说明了这个问题:

// MAIN.CPP
#include "Test.h"

int main ()
{
    Test test;
    map<int, pthread_mutex_t>* mutexHash = test.getMutexHash();


    return 0;
}

// TEST.H
#include <map>
#include <pthread.h>

using namespace std;

class Test
{
  public:
    map<int, pthread_mutex_t>* getMutexHash();
  private:
    static map<int, pthread_mutex_t> mutexHash;
};

// TEST.CPP
#include "Test.h"

map<int, pthread_mutex_t>* Test::getMutexHash()
{
    return &mutexHash;
}

编译时,我没有收到任何错误或警告;但是在链接时,我收到此错误:

Test.o: In function `Test::getMutexHash()':
Test.cpp:(.text+0x9): undefined reference to `Test::mutexHash'
collect2: ld returned 1 exit status

有人可以帮我吗?

【问题讨论】:

标签: c++ static linker


【解决方案1】:

您已声明mutexHash 存在,但尚未定义它。你需要给test.cpp添加一个定义:

map<int, pthread_mutex_t> Test::mutexHash;

【讨论】:

  • 哇!有效。我不知道我必须将静态变量定义为“前向声明”。谢谢!我已经陷入这个问题一段时间了=)
猜你喜欢
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
相关资源
最近更新 更多