devxlogo

Constructor with static members in library

Constructor with static members in library

Question:
Background: Digital UNIX 3.2g, Alpha platform, latest GNU.

From the FAQ, I know that you are supposed to declare static member variables externally from the declaration and inonly one place. But our group has run into a problem with that.

The code below works fine when it’s just a couple of normal files compiled together. But what to do when that class is part of a library? Defining it in the related source causes us core dumps, which we traced to the fact that the static member class constructors did not run when placed in the library. If the static member class variables are defined in the main program, everything works fine again, but it just plain feels wrong for the application to have intricate knowledge of library class internals. Is there a recommended method of doing what we are without “exposing ourselves”?

Here’s a version of what I’m talking about in case my description lacked info or used poor terminology. The Test.C file would normally be part of thelibrary.

Test.h ———-class StaticTest {public:    StaticTest();    ~StaticTest();};class MyContainer {public:    MyContainer();    ~MyContainer();private:    static StaticTest _list [3];    static StaticTest _single;};Test.C ———-#include #include “Test.h”StaticTest::StaticTest() { cerr << "StaticTest" << endl; }StaticTest::~StaticTest() {}#if LOOKS_GOOD_BUT_DOESNT_WORKStaticTest MyContainer::_list[3];StaticTest MyContainer::_single;#endifMyContainer::MyContainer() { cerr << "MyContainer" << endl; }MyContainer::~MyContainer() {}Main.C -----------#include "Test.h"#if WORKS_BUT_FEELS_WRONGStaticTest MyContainer::_list[3];StaticTest MyContainer::_single;#endifint main (int, char *[]){    MyContainer container;    return 0;}

Answer:
What you are trying to do is perfectly OK and normal..

I know of at least one platform (VxWorks) where these have to be treated specially because the platform requires it to be so.

I would like to know on what platform you tried to do this , so I can try to run it on the same and investigate the problem furtherC++Pro

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist