Calling a macro only once in the project

1.1k Views Asked by At

I am trying to set up the easylogging++ in a project, and I run into the following issue:

Macro INITIALIZE_EASYLOGGINGPP should be called only once in the project. Now, if I call this macro from my main.cpp and only include easylogging++.h in main.cpp - everything works fine. However, when I try to include easylogging++.h in more .cpp files, I get linker issues with undefined references (as if the macro hasn't been called). If I place the call to this macro in a file that is alphabetically before the main.cpp, linker resolves everything normally. In the linking phase objects are sorted alphabetically.

Is there a nice way to solve this issue? Or will I have to try to force a different order of files at linking time?

I am not that much experienced with this sort of issues, tried googling it, couldn't find the solution. If there is already a similar question, sorry, couldn't find it.

Thanks for the help!

3

There are 3 best solutions below

0
On BEST ANSWER

Some programmer dude was right, there isn't a problem with linking+macroes.

After trying to recreate the minimal example to post it here, I realized there was a bug in the CMakeLists.txt which caused the main.cpp (in which I expanded the easylogging++ macro) to be excluded from the build under some circumstances.

Thank you all for your time and sorry for the stupid question.

0
On
#ifndef INITIALIZE_EASYLOGGINGPP
#define INITIALIZE_EASYLOGGINGPP SomeLogic
#endif

#ifndef will check if the token has already been defined and in that case this section will be ignored.

0
On

Maybe you could wrap the call in a function that you invoke using std::call_once(), for example:

void setup_logging() {
  static std::once_flag once;
  std::call_once(once, [] () { INITIALIZE_EASYLOGGINGPP(); });
}

That way you can call setup_logging() multiple times, but the macro is invoked once.