0

I know similar questions have been asked, but none address this issue. I want to create a globals struct and initialize it with default values. I implemented it as below, but the project won't build.

I've tried everything I can think of, most notably moving the "extern" declaration of *gxg in and out of the header guard and changing the struct to a class, but get the same results: the project won't build because of duplicate symbols for the globals constructor. It builds if I don't use it in more than one .cpp file, or if I don't include a constructor or destructor in the struct's implementation file.

//  globals.hpp

#ifndef globals_hpp
#define globals_hpp

struct gxGlobals{
    double radius;
    bool easement;

    gxGlobals(); // constructor

} ;

extern "C" gxGlobals *gxg;

#endif /* globals_hpp */

—————————————

//  globals.cpp

#include "globals.hpp"

gxGlobals::gxGlobals():
    radius(24),
    easement(false)
    {};

———————————

//  main_file.cpp

#include "globals.hpp"

gxGlobals *gxg = new gxGlobals();

———————————

//  other_file.cpp

#include "globals.hpp"

// ERROR: Duplicate symbol gxGlobals::gxGlobals()

I can include globals.h in one file, but not in two or more. It also works if I remove the self-initialization in the .cpp file.

There are too many members in the actual struct to make an initializer list practical, so my last option is a function that runs on startup that plugs all of the default values in. Am I mistaken that this should work?

RJGraffix
  • 1
  • 3
  • 1. Why are you using globals? Bad idea - see http://stackoverflow.com/questions/484635/are-global-variables-bad 2. Why are you using `extern "C"` – Ed Heal Jun 11 '16 at 05:06
  • Thanks for the advice, Ed. I'm writing a plugin for Adobe Illustrator, and have been using globals in them for about 20 years based on the examples in their SDKs. As of the 2015 version, they still use globals and `extern "C"`. I've been using fewer globals as I make my code more modular, but many remain because the plugin is so interactive; it monitors the mouse, keyboard, and settings palettes simultaneously, and adjusts its behavior immediately and accordingly. Perhaps a sort of "controller" class would work better. I'm open to new ideas. – RJGraffix Jun 11 '16 at 22:21

0 Answers0