0

Hello in my class Bullet I declare active as false when the bullet isn't active and true when it is. In my other class that isn't connected to my Bullet class in any way I want to use the bool member active and change it, how can I do that?

Im getting the error

Error 18 error LNK2001: unresolved external symbol "public: static bool Bullet::active" (?active@Bullet@@2_NA) C:\Skolarbete\Programmering i C++\ProjectTemplate\ProjectTemplate\Alienrow.obj ProjectTemplate

Declaration: static bool active;

When I use it: Bullet::active = false;

Im quite new too C++ so don't hate! Appreciate all the help I can get :D

2
  • are you using some library? Commented Mar 25, 2014 at 23:32
  • Im including the bullet.h file in the file I want to use active, if thats what you mean? Commented Mar 25, 2014 at 23:33

3 Answers 3

1

A static variable inside a class is actually an external declaration. You still need the variable definition. This is similar to C external variables.

So in the .h file:

class Bullet
{
public:
    static bool active;
};

and in the .cpp file, at global scope:

bool Bullet::active = false;

The lack of the variable definition (not declaration) is deduced because your error message actually comes from the linker, not the compiler.

Sign up to request clarification or add additional context in comments.

Comments

0

static class members need to be defined somewhere, in your case there must be a

bool Bullet::active;

definition in a cpp file of your choice (a file which #includes the class declaration).
You can think of static members as global variables which happen to be in the "namespace" of the class. The class declaration as such doesn't create any objects, not even the static members, it's just, well, a declaration.

Comments

0

You forgot to specify the type of the variable (that is to define the object). Write

bool Bullet::active = false;

instead of

Bullet::active = false;

That is at first you have to define the object and only after that you can assign it.

As for the statement you showed

Bullet::active = false;

then it is not a definition of active. It is an assignment statement.

Take into account that the definition should be placed in some module. If you will place it in the header you can get an error that the object is already defined.

2 Comments

Then it says 'bool Bullet::active' : redefinition' "
@Prolle You must exclude this definition from the hader and place it in some module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.