0

I would like to use a static std::queue (static std::queue<Efeito*> efeitos;) to be called in my static functions in the same class, but I tried several ways and the one thing I got is a error:

undefined reference to EfeitosVisuais::efeitos'

Here is the code:

#include <iostream>
#include <queue>
#include "Efeito.h"
#include "Efeitos Visuais/EfeitoPedregulho.h"


class EfeitosVisuais {
public:
    static std::queue<Efeito*> efeitos;
    static void AddEfeito(double x, double y,char efeito){
        switch(efeito){
            case 'P':
                EfeitoPedregulho *pedregulho = new EfeitoPedregulho(x,y);
                efeitos.push(pedregulho);
                break;
        }
    }

    static void Atualizar(int tempodejogo) {
        if(!efeitos.empty()) {
            for (int i = 0; i < efeitos.size(); i++) {
                efeitos.front()->Atualiza(tempodejogo);
                efeitos.push(efeitos.front());
                efeitos.pop();
            }
        }
    }
};

How to solve it?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 7
    Where did you define `std::queue EfeitosVisuais::efeitos;` ? It has to be *somewhere*. As it is not an instance member, its formal definition must appear in with static linkage *once* in some translation unit, pretty much exactly as I just showed, outside the class. – WhozCraig May 30 '20 at 21:52
  • Does this answer your question? [undefined reference to Base::object linker error @ c++ w/ freeglut](https://stackoverflow.com/questions/9074073/undefined-reference-to-baseobject-linker-error-c-w-freeglut) – Waqar May 30 '20 at 21:54
  • since C++17 add `inline` to the declaration – M.M May 30 '20 at 23:48

1 Answers1

3

static data members needs to be defined separately. Just define your static variable outside the class in the .cpp file:

std::queue<Efeito*> EfeitosVisuais::efeitos;

Update

As @Remy Lebeau said in the comments, The variable must have exactly one definition so that it doesn't violate ODR - One definition rule. This is why it is important that you define it in the .cpp file because if it's in the .h file, the header file may be included in multiple places which will result in an error.

As @WBuck said, Since c++17 you can use inline variables.:

inline std::queue<Efeito*> efeitos;

Also note that if you use constexpr, the variable is implicitly inline.

Waqar
  • 8,558
  • 4
  • 35
  • 43
  • 1
    "*Just define your static variable outside the class*" - this is not good enough on its own. For instance, defining it after the class declaration in the same header file would be bad. It is important to define it someplace where it will be seen only one time, such as in a cpp file. – Remy Lebeau May 30 '20 at 22:31
  • 1
    @RemyLebeau Thats true unless they specify `inline` (and they're using `C++17`) – WBuck May 31 '20 at 00:44
  • @RemyLebeau thanks, I added this to the answer – Waqar May 31 '20 at 15:04