Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Linker error when using O1 optimization

In an already existing and quite large project, I'm enabling the gcc compiler optimization O1.

Without this option, everything builds, links and runs fine. with the option enabled, the main executable compiles and links, but I get linker errors when linking one of the unit tests.

Between these 2 compile runs, I didn't change any code or make files, only the O1 optimization flag.

The error that I get is:

Configuration.a(Builder.o): In function `Builder::Create() const':
Builder.cpp:123: undefined reference to `Factory::Instance()'

Somewhere during the linking process, it encounters this line (line 123) of Builder.cpp: cpp file

pObject = Factory::Instance()->CreateObject();

(Besides the linker error of the Instance function, I also get one from the CreateObject function)

When I look at the Factory, I see: header file

class Factory { public:
    static Factory* Instance(); << rest of the file >>

And in the cpp file

Factory* Factory::sInstance = 0;

Factory* Factory::Instance() {
    // Check if this is the first call
    if (sInstance == 0)
    {
        // Create only instance
        sInstance = new Factory();
    }

    // Address of the instance
    return sInstance; }

First I tried a clean and rebuild, but that didn't do anything. also I used nm to make dumps of the used symbols of Factory.o (one with and one without optimization) and compared these.

I see that some symbols are removed, but not the Factory::Instance() one. I do see something with the address changed regarding this function, but I won't expect that to be a problem.

Also via Google I found a couple of possibilities, but I couldn't find something that matched my problem.

does anyone have an idea of how to find this problem?

like image 342
Rob Avatar asked Nov 13 '22 09:11

Rob


1 Answers

Configuration.a(Builder.o): In function Builder::Create() const': Builder.cpp:123: undefined reference toFactory::Instance()'

Since you've verified that Factory::Instance() is defined in Factory.o, and since you are obviously using archive libraries, my crystal ball says that whatever library contains Factory.o is on command line before Configuration.a, whereas it should be after it.

The order of archive libraries on command line matters.

like image 145
Employed Russian Avatar answered Nov 15 '22 05:11

Employed Russian