Please show me how to make a global const object construct only once.

Hi my problem is one of my global const objects is getting constructed more than once.
1
2
3
4
5
6
7
8
9
10
11
12
13

#ifndef _UTILS_HPP_
#define _UTILS_HPP_

class TestClass{
	public: TestClass(){ 
		static int Cnt = 0;
		++Cnt; }
};

const TestClass TestObj;

#endif 


Now this file is one of the most oft called files in my project (called like 10x).
It ends up constructing the const TestObj 10x which can be tracked by Cnt;

Is there a way of declaring a global object that can't be constructed 10x times?
This happens even if the const TestClass is static.
Last edited on
one of my global const objects is getting constructed more than once
I seriously doubt it. Post your main().
Absolutely it is. Do not declare variables in header files.

Every .cpp file that includes Utils.hpp directly or indirectly is getting its own personal
copy of TestObj.

What? Surely the guard (#ifndef... #endif) would stop that?
a.cpp includes Utils.hpp and b.cpp includes Utils.hpp.

include guards don't stop that.
Topic archived. No new replies allowed.