简体   繁体   English

C++ 共享库初始化全局变量

[英]C++ global variable initialization by shared library

shared.h共享.h

    #pragma once
    
    extern int uninitialized_variable;
    extern int initialized_variable;
    
    void print();

shared.cpp共享.cpp

    // shared.cpp
    #include "shared.h"
    #include <stdio.h>
    
    int uninitialized_variable;
    int initialized_variable = 8;
    
    void print() {
        printf("%d\n", uninitialized_variable);
        printf("%d\n", initialized_variable);
    }

main.cpp主文件

    #include "shared.h"
    #include <stdio.h>
    
    
    int main() {
        printf("%d\n", uninitialized_variable);
        printf("%d\n", initialized_variable);
        print();
    }

g++ -O0 -pedantic -std=c++11 -fPIC shared.cpp -c -o shared.o
g++ -shared -o libshared.so shared.o

g++ -O0 -pedantic -std=c++11 main.cpp -L. -lshared

When I run./a.out, the result is 0 8 0 8. But I can't find the reason why initialized_variable is 8.当我运行./a.out时,结果是0 8 0 8。但是我找不到initialized_variable为8的原因。

Since I used gbd the check where exactly is initialized_variable ,and found that it is in the.bss in a.out。But in the.init section of the libshared.so, i can't find any code to do the initialization of the initialized_variable in a.out's.bss.由于我用gbd检查了initialized_variable到底在哪里,发现在a.out的.bss中。但是在libshared.so的.init部分,我找不到任何代码来做初始化a.out's.bss 中的initialized_variable

Who and when the initialized_variable is initalized?谁以及何时initialized_variable了 initialized_variable?

It's provided as raw data in the .data segment:它在.data段中作为原始数据提供:

Disassembly of section .data:

....

0000000000004028 <initialized_variable>:
    4028:   08 00                   or     %al,(%rax)
    402a:   00 00                   add    %al,(%rax)

Ignore the assembly as this is not executable data.忽略程序集,因为这不是可执行数据。 Note that the offset where initialized_variable lives contains the four bytes (in hex here): 08 00 00 00. Interpreted as a 4-byte signed little-endian integer, this is the value 8.请注意, initialized_variable所在的偏移量包含四个字节(此处为十六进制):08 00 00 00。解释为 4 字节有符号 little-endian integer,这是值 8。

Quite simply, the value is 8 as soon as the library is mapped into memory.很简单,一旦库映射到 memory,该值就是 8。 No additional instructions are required to initialize it.初始化它不需要额外的指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM