0

I'm having a strange situation where using a global object appears to cause unrelated linker errors.

My setup is as follows:

// globals.h
#ifndef GLOBALS_H
#define GLOBALS_H

class Singleton
{
...
};

extern Singleton* g_object;
#endif

// globals.cpp

#include "globals.h"

Singleton* g_object = new Singleton();

// somefile.cpp

#include "globals.h"

void function()
{
    g_object->do_some_stuff();
}

It looks like that when I try to use g_object somewhere, I get a lot of "undefined references" from the linker, but they all refer to some other, unrelated parts of the project and have nothing to do with my class or object or the functions that use it.

I feel like I'm missing something obvious and it screws up the objects somehow, but I can't quite figure out what, as far as I can tell declaring a global in an .h file and then providing the definition in a .cpp is the approved way of creating globals, what am I doing wrong?

P.S.

I use the following flags: -c -v -Wall -Wno-strict-aliasing -Weffc++ -Woverloaded-virtual -Wshadow -Wuninitialized -fstack-protector -fshort-wchar -fvisibility=hidden -fms-extensions -xc++ -fno-strict-aliasing -std=c++11 -fpermissive -Wno-narrowing -pthread -g -fPI

Maxim
  • 335
  • 5
  • 14
  • Please change `exten` to `extern` in your first code block :) – L. F. Feb 05 '19 at 00:01
  • Can you show us your flags when compiling? – L. F. Feb 05 '19 at 00:03
  • @L.F. I've added the compiler flags – Maxim Feb 05 '19 at 00:08
  • It would also be helpful if you provided the command you are using for linking... since that is where the errors are mentioned. (And why is the header being brought in with `` with angled-brackets? Very odd.) – Eljay Feb 05 '19 at 00:08
  • @Eljay Whoops, the include brackets were a typo – Maxim Feb 05 '19 at 00:10
  • without a [MVCE](https://stackoverflow.com/help/mcve) it's hard to say, as your example cannot manifest the problem per se. – Jack Feb 05 '19 at 00:11
  • Unrelated: `Singleton* g_object = new Singleton();` suggests that a program could ask for multiple instances of `Singleton`. This doesn't jive with the common usage of the term singleton in programming. [Here's a link to an excellent way to make a singleton](https://stackoverflow.com/a/1008289/4581301) – user4581301 Feb 05 '19 at 00:12
  • @user4581301 yes, OP way is definitely a bad choice for a singleton but this should compile in any case. – Jack Feb 05 '19 at 00:12
  • 1
    The flags you have shown us are not relevant. They are for compilation only. Undefined reference errors are linkage errors. We have no information about your linkage. [mcve] needed. – Mike Kinghan Feb 05 '19 at 09:58

0 Answers0