静态初始化和销毁​​静态库的全局变量不会发生在g ++ [英] Static initialization and destruction of a static library's globals not happening with g++

查看:270
本文介绍了静态初始化和销毁​​静态库的全局变量不会发生在g ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到一段时间以前,我认为.a静态库只是一个.o对象文件的集合,只是归档它们,而不是使它们处理不同。但是与.o对象链接,并与包含.o对象的.a静态库链接显然不一样。我不明白为什么...

Until some time ago, I thought a .a static library was just a collection of .o object files, just archiving them and not making them handled differently. But linking with a .o object and linking with a .a static library containing this .o object are apparently not the same. And I don't understand why...

让我们考虑下面的源代码文件:

Let's consider the following source code files:

// main.cpp
#include <iostream>
int main(int argc, char* argv[]) {
    std::cout << "main" << std::endl;
}


// object.hpp
#include <iostream>
struct Object
{
    Object() { std::cout << "Object constructor called" << std::endl; }
    ~Object() { std::cout << "Object destructor called" << std::endl; }
};


// object.cpp
#include "object.hpp"
static Object gObject;

让我们编译并链接并运行此代码:

Let's compile and link and run this code:

g++ -Wall object.cpp main.cpp -o main1
./main1
> Object constructor called
> main
> Object destructor called

调用全局gObject对象的析构函数。

The constructor an the destructor of the global gObject object is called.

现在,让我们从代码中创建静态库,并在另一个程序中使用(链接):

Now let's create a static library from our code and use (link) it in another program:

g++ -Wall -c object.cpp main.cpp
ar rcs lib.a object.o
g++ -Wall -o main2 main.o lib.a
./main2
> main




  • gObject的构造函数和析构函数不会被调用...为什么?

  • 如何让它们自动调用?

    • gObject's constructor and destructor are not called... why?
    • How to have them automatically called?
    • 感谢。

      推荐答案

      .a .o ,但它们不会链接,除非您从主应用程序中引用它们。

      .o

      .a static libraries contain several .o but they are not linked in unless you reference them from the main app.
      .o files standalone link always.

      因此,链接器中的 .o 文件总是进入,但是 .a 文件只引用 .o 对象文件。

      So .o files in the linker always go inside, referenced or not, but from .a files only referenced .o object files are linked.

      注意,静态全局对象不需要被初始化,直到你实际上引用编译单元中的任何东西,大多数编译器将在main之前初始化它们,但是唯一的要求是它们在任何函数之前被初始化的编译单元被执行。

      As a note, static global objects are not required to be initialized till you actually reference anything in the compilation unit, most compilers will initialize all of them before main, but the only requirement is that they get initialized before any function of the compilation unit gets executed.

      这篇关于静态初始化和销毁​​静态库的全局变量不会发生在g ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆