6

Есть динамическая библиотека в которой определена глобальная переменная. Также определена функция DllMain Которая использует эту глобальную переменную:

std::string g_value("value");

//Windows 
BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID /*lpReserved*/)
{
  //использование g_value;
}

//Linux
void start() __attribute__ ((constructor));
void start()
{
   //использование g_value;
}

Под Windows сначала инициализируются глобальные переменные а потом уже начинает выполнятся DllMain (это всегда так или порядок не определен строго?). Под Linux наоборот сначала выполняется start, а потом глобальные переменные.

Можно ли задать порядок выполнения? Сначала глобальные переменные а потом start?

1 ответ 1

5

Нужно задать порядок инициализации:

std::string g_value __attribute__((init_priority(101))) = "value";

void start() __attribute__((constructor(102)));

void start()
{
  // использование g_value;
}

Решение взято отсюда:

Bug 52477 - Wrong initialization order? __attribute__((constructor)) vs static data access

По результатам обсуждения бага, была дополнена документация (6.31.1 Common Function Attributes) и сказано, что для С++ порядок инициализации глобальных данных и функций с атрибутом constructor не определён и рекомендуется использовать атрибут init_priority:

The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () completes or exit () is called. Functions with these attributes are useful for initializing data that is used implicitly during the execution of the program.

You may provide an optional integer priority to control the order in which constructor and destructor functions are run. A constructor with a smaller priority number runs before a constructor with a larger priority number; the opposite relationship holds for destructors. So, if you have a constructor that allocates a resource and a destructor that deallocates the same resource, both functions typically have the same priority. The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects (see C++ Attributes). However, at present, the order in which constructors for C++ objects with static storage duration and functions decorated with attribute constructor are invoked is unspecified. In mixed declarations, attribute init_priority can be used to impose a specific ordering.

1
  • 1
    Интересно, как эти init_priority реализуются на уровне линкера (порядок в котором адреса секций .ctors, .init попадают в соответствующие массивы)?
    – avp
    19 дек 2017 в 21:01

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.