0

At the moment I am trying to declare a global object in c++ as follows:

in globals.h

#pragma once
#include "Class.h"

extern Class *obj;

then in a separate file called globals.cpp I have

#include "globals.h"
Class *obj;

And then in main.cpp I have

#include "globals.h"

But the compiler throws this error at me

in globals.h: error C2143: syntax error : missing ';' before '*'    

I don't understand this since this post: c++ global object explains that this is the way it's done.

Community
  • 1
  • 1

2 Answers2

1

C2143 usually means you the compiler is not finding the definition/declaration of class Class before the variable declaration.

One way you can have it is that you have probably missed the semicolon at the end of the class definition in class.h.

In class.h

You have

class Class
{
    ....
}

You have forgotten the semicolon above.

Change to

class Class
{
    ....
} ;

If this is not the case, is there any other reason the definition of class Class is not found in class.h - is it inside #ifdefs or something?

Try compiling with /P and then open main.i in an editor and check if you see the declaration of class Class before the extern statement.

user93353
  • 13,733
  • 8
  • 60
  • 122
1

The problem is with class.h including globals.h. You say that if you do this, the program compiles but throws an access violation. Then there's an error in the logic, that's a different issue.

Fix compiler errors first. The access violation is probably because you didn't initialize the global correctly - i.e. as you have it, it's just a NULL pointer.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625