Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static class in C++

Tags:

c++

class

static

In the header I declared

#ifndef SOUND_CORE
#define SOUND_CORE

static SoundEngine soundEngine;

...

but the constructor for SoundEngine gets called multiple times, how is it possible, when it's declared as global static

I call it as

#include "SoundCore.h"

and use it directly

soundEngine.foo()

thank you

like image 801
Peter Lapisu Avatar asked Dec 05 '22 21:12

Peter Lapisu


1 Answers

I would use extern instead of static. That's what extern is for.

In the header:

extern SoundEngine soundEngine;

In an accompanying source file:

SoundEngine soundEngine;

This will create one translation unit with the instance, and including the header will allow you to use it everywhere in your code.

// A.cpp
#include <iostream>
// other includes here
...
extern int hours; // this is declared globally in B.cpp

int foo()
{
hours = 1;
}


// B.cpp
#include <iostream>
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line

int main()
{
foo();
}
like image 149
rubenvb Avatar answered Dec 31 '22 02:12

rubenvb