Resolution of a static variable during assembly

I have files that are related:

basic.h

#pragma once extern const string APPLICATION_NAME; 

application.cpp

 #include "basic.h" const string APPLICATION_NAME = "MyApplication"; ............ 

ErrorTables.h

 class ErrorTable { public: ErrorTable(); private: map <index, errorRecord> _errorTable; }; 

ErrorTables.cpp

 #include "basic.h" ErrorTable TheErrorTable; ErrorTable::ErrorTable() { ... _errorTable[errorIndex] = errorRecord(APPLICATION_NAME + " hit some error."); ... } 

This code can be created and run OK in Visual Studio. When I use GCC, it can be created but not executed at runtime. The problem is with TheErrorTable, which has a static link and created before main () was run; it cannot resolve the variable APPLICATION_NAME. If I hide it with a local variable, everything works fine.

Is there a GCC flag that forcibly resolves a static variable at build time or implements Visual Studio behavior in some other way?

0
source share
1 answer

The problem is TheErrorTable , which has a static link and is created before main () is run; it cannot resolve the variable APPLICATION_NAME .

It is right. Initially, either TheErrorTable or APPLICATION_NAME initialized, and you cannot fix this.


Make ErrorTable Not Global. You cannot determine the order of static initialization through TU, and even if you could just make the code more complex to follow.

I'm sorry to say this, but ErrorTable can benefit from the singleton pattern here (because the static function has a normal initialization order), at least to the extent that this solution is closest to your existing code.


Update

As @godexsoft mentioned, you can get around this by using constant initialization and making APPLICATION_NAME a char const* rather than std::string ; then your initializer will be the initializer of the constant expression without calling the constructor and as such will be called through TUs; before any ErrorTable guaranteed. ( Really? Yes. )

+2
source

Source: https://habr.com/ru/post/905257/


All Articles