0

I am quite new to c++ programming, and made a little Logging system yesterday. Now I struggle with getting it running. I've tried a lot of stuff none seemed to have worked. The problem I'm encountering is, that the logging system starts up for every cpp file I include the "Core.h" file in. Core.h:

#pragma once

#ifndef CORE_H_
#define CORE_H_


#include "logger/Log.h"
#include <iostream>
#include <string>
#include <memory>

static std::shared_ptr<athena::Log> l (new athena::Log());
//static athena::Log l = athena::Log();

#endif // !CORE_H_

My main method looks like this right now:

#include <iostream>
#include "Core.h"

int main(int argc, char* argv[])
{
    l->log("Hello World!");
    l->warn("Hello World!");
    l->err("Hello World!");
    l->crit("Hello World!");
    l->debug("Hello World!");

    system("PAUSE");
    return 0;
}

I also have one other file right now, in which "Core.h" is included. And every time the Logging thing starts up it Prints: Log Initalized! in the console. Thats why my output looks like this rn (with color of course):

 7/34/55: Log initialized!
 7/34/55: Log initialized!
 7/34/55: Hello World!
 7/34/55: Hello World!
 7/34/55: ERROR: Hello World!
 7/34/55: CRIT: Hello World!
 7/34/55: DEBUG: Hello World!
Drücken Sie eine beliebige Taste . . .

Its propably laughably easy to fix. I just dont have a clue.

In conclusion i want there to be one instance of this logger, which i can access anywhere, where "Core.h" ist included.

Luh0
  • 105
  • 8
  • Declare the object as `extern` in a header file (at file scope, outside any function). Include that header file in every source file that needs to use the object. In exactly one source file in your project, also define the object (essentially, declare it at file scope, but without the `extern` keyword) and initialise it as needed. The `extern` declarations them, in every source file, declare that the object exists. The single definition is needed to make the object actually exist. – Peter Mar 06 '22 at 06:54
  • 2
    This is the expected behaviour if you declare a `static` variable like that in a header. It will create one instance of that variable in each translation unit that you include the header in. If you're using c++17 you can replace `static` with `inline` to get the behaviour you are looking for. – super Mar 06 '22 at 07:52
  • Giving the user direct access to the logger lifetime is bad practice. If you add `l = nullptr;` somewhere in your code, other code may just crash. You may want to use ["magic static"](https://stackoverflow.com/a/11711991/2991525) here... – fabian Mar 06 '22 at 10:02

0 Answers0