Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static class member not initialized in a * static library *

I'm currently facing an annoying issue with C++.

Actually, I don't even understand why I didn't face it for the past 20 years :(

In my current context, we heavily use c++ executables (mostly in Linux embedded systems) statically linked with our proprietary static libs. And we do use static libs for technical and optimization reasons.

Over the past years, indeed, I used to create shared libs though...

So I began to write some classes with static class members. Such as follow:

class Inner
{
public:
   Inner()
   {
     std::cout << "CTOR Inner" << std::endl;
   }
};

class A
{
static Inner _inner;

...
};

// in the .cpp

Inner A::_inner;

///////////////////////

Very basic use-case, isn't it ?

But in my unit-tests, linked with the lib, I can't see the std::cout statement in the console. Whereas, if I move my class Inner and A into the executable source-code...it works fine.

I'm sure it's a very basic issue and I realize I've never faced over the past years. Is it an issue related to the compilers ? Please note that I tested both cases on Windows and Linux (Debian, Gcc 4.9).

Any idea is welcome.

Z.

like image 428
Zyend Avatar asked Mar 01 '17 20:03

Zyend


1 Answers

You have to actually use A::_inner somehow or that part of code won't be included. Either that or use something else in that file. Linkers don't have to link in translation units that are never used, even if they'd have observable side effects.

How to force inclusion of "unused" object definitions in a library

like image 160
Edward Strange Avatar answered Sep 18 '22 10:09

Edward Strange