来自主可执行文件的 GCC 属性 __attribute__ ((constructor)) 在链接库构造函数之后运行

GCC attribute __attribute__ ((constructor)) from main executable runs after linked libraries constructors

我注意到链接到我的应用程序的共享对象的构造函数将始终 运行 在我的应用程序构造函数之前,即使我的应用程序具有较低的优先级(即:较高优先级);例如,假设这个程序:

#include <stdio.h>

static void __attribute__ ((constructor (101))) test() {
    printf("test\n");
}

int main(int argc, char *argv[]) {
    return 0;
}

正在链接以下共享对象:

#include <stdio.h>

static void __attribute__ ((constructor (102))) test_so() {
    printf("test so\n");
}

我预计输出为:

test
test so

相反,输出是相反的。
有什么理由吗?我找不到任何文档。

Is there any reason why?

事实:

  • __attribute__((__constructor__)) 基本上将指向函数的指针添加到某些 ELF 部分
  • 每个 ELF 文件都有一个单独的 DT_INIT 或 DT_INIT_ARRAY 部分。
  • 每个 ELF 文件按顺序加载,依赖项在可执行文件之前加载。
  • 因此共享库构造函数将 运行 在可执行之前。
  • __attribute__((__constructor__(this_number))) 的排序仅限于一个 ELF 文件,因为编译器可以在那里重新排序它们。

could not find any documentation.

记录在https://refspecs.linuxfoundation.org/elf/elf.pdf :

Initialization and Termination Functions

After the dynamic linker has built the process image and performed the relocations, each shared object gets the opportunity to execute some initialization code. All shared object initializations happen before the executable file gains control.