11

I wanna create a global object in cpp program, how do I do that? Is this right? in "global_obj.h"

#include "class.h"
Class obj;

in "main.cpp"

extern Class obj;
Puppy
  • 141,834
  • 35
  • 244
  • 454
Rn2dy
  • 3,922
  • 12
  • 41
  • 59
  • 2
    Your one answer is absolutely correct. The `extern` declaration belongs in the header file. The non-`extern` definition belongs in exactly one `.cpp` file. – Omnifarious Feb 07 '11 at 04:20

1 Answers1

19

We declare our globals as extern in a header file, in your case: global_obj.h, and the actual global variable in a source file: global_obj.cpp. In separate source files we #include "global_obj.h" to have access to them.

It should look like this:

global_obj.cpp

Class obj;

global_obj.h

extern Class obj;

main.cpp

#include "global_obj.h"
Marlon
  • 19,321
  • 11
  • 64
  • 96