使用指向另一个类的静态指针时出现错误LNK2001

时间:2016-12-07 22:46:40

标签: c++ pointers sdl sdl-2

我有两节课。首先(Spawn.cpp只打印调用类的消息):

// Spawn.h
#pragma once
#ifndef SPAWN_H_
#define SPAWN_H_
class Spawn {// const + destr only};
#endif /* SPAWN_H_ */

第二:

// Thread.h
#include "Spawn.h"
#pragma once
#ifndef THREAD_H_
#define THREAD_H_

class Thread
{
public:
    Thread();
    virtual ~Thread();

private:

    void Initialise();
    static int WindowThread(void *ptr);
    static int ConsoleThread(void *ptr);
    static Spawn * CreateSpawner();
    static Spawn * pSpawner; // if the pointer is non-static, it can't be
                             // used within static function.

    SDL_Thread * pConsoleThread;
};
Spawn * Thread::pSpawner = nullptr;
#endif /* THREAD_H_ */

代码本身:

// Thread.cpp
#include "stdafx.h"
#include "Thread.h"

Thread::Thread() { Initialise(); }

void Thread::Initialise() { // call of the threads here }


int Thread::WindowThread(void * ptr)
{
    while (true)
    {
        // I want to access pointer pSpawner here
    }
    return 1;
}


int Thread::ConsoleThread(void * ptr)
{
    // Main console loop
    while (true)
    {
        /* Spawn handling */
        if (CUI.INP == "spawn")
        {
            pSpawner = CreateSpawner(); // I am unable to access that
                                        // pointer here as well
        }
    }
    return 2;
}


Spawn * Thread::CreateSpawner()
{ 
    // Singleton initialisation:
    Spawn * m_pSPAWNER = new Spawn;
    return m_pSPAWNER;
}

我正在使用SDL外部库创建两个线程,这些线程是static int函数,所以它只能使用静态指针(如果我使用标准指针,则错误就是指针必须是静态的,但我使用Visual Studio 2015得到的错误:

Error LNK2001 unresolved external symbol "private: static class Spawn * Thread::pSpawner"

Error LNK1120 1 unresolved externals

我已经尝试过这里完成的建议,但没有结果(你可以在Thread.h中找到声明和定义): error LNK2001: unresolved external symbol public: static class

C++ vector issue - 'LNK2001: unresolved external symbol private: static...'

这个问题的答案没有帮助(当我尝试所有建议时,我会在这里留下更新):

What is an undefined reference/unresolved external symbol error and how do I fix it?

1 个答案:

答案 0 :(得分:1)

  1. 此错误消息非常清楚,您无法定义全局。最好在cpp文件中定义全局。因为每次包含标题时都可以定义标题。

    // Thread.cpp
    Spawn * Thread::pSpawner = nullptr;
    
  2. 使用#pragma once#ifndef毫无用处。只做其中一个。

    #pragma once
    

    顺便说一句,如果你使用#ifndef ALL 必须在#if内。您已将"Spawn.h"包含在外部,它可以产生无限循环的包含。

    "There is no advantage to use of both the #include guard idiom and #pragma once in the same file."