如何防止我的“未使用”全局变量编译出来? [英] How do I prevent my 'unused' global variables being compiled out?

查看:809
本文介绍了如何防止我的“未使用”全局变量编译出来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用静态初始化来简化在C ++中用工厂注册一些类的过程。不幸的是,我认为编译器优化了未使用对象,这意味着在它们的构造函数中做有用的工作。有没有办法告诉编译器不优化一个全局变量?

I'm using static initialisation to ease the process of registering some classes with a factory in C++. Unfortunately, I think the compiler is optimising out the 'unused' objects which are meant to do the useful work in their constructors. Is there any way to tell the compiler not to optimise out a global variable?

class SomeClass {
    public:
        SomeClass() {
            /* do something useful */
        }
};

SomeClass instance;

我的断点在SomeClass的构造函数不会命中。在我的实际代码中,SomeClass是一个头文件,而实例是在一个源文件中,或多或少单独。

My breakpoint in SomeClass's constructor doesn't get hit. In my actual code, SomeClass is in a header file and instance is in a source file, more or less alone.

编辑:正如KJAWolf猜到的,编译成一个静态库,不是可执行文件。其目的是为静态库提供的一些类型注册一个静态的类型列表及其创建者,以便工厂在构建时读取。因为这些类型是与lib一起提供的,所以将这个代码添加到可执行文件是不可取的。

As guessed by KJAWolf, this code is actually compiled into a static lib, not the executable. Its purpose is to register some types also provided by the static lib with a static list of types and their creators, for a factory to then read from on construction. Since these types are provided with the lib, adding this code to the executable is undesirable.

我发现通过将代码移动到另一个包含其他现有代码的源文件,它工作正常。看来,拥有一个纯粹由这些全局对象组成的文件是导致问题的原因。

Also I discovered that by moving the code to another source file that contains other existing code, it works fine. It seems that having a file purely consisting of these global objects is what's causing the problem. It's as if that translation unit was entirely ignored.

推荐答案

编译器不允许优化全局对象。

即使它们从未使用过。

The compiler is not allowed to optimiza away global objects.
Even if they are never used.

您的代码中还发生了其他事情。

现在,如果您使用全局对象构建了静态库,并且该全局对象未引用该可执行文件不会被链接器拉入可执行文件。

Somthing else is happening in your code.
Now if you built a static library with your global object and that global object is not referenced from the executable it will not be pulled into the executable by the linker.

这篇关于如何防止我的“未使用”全局变量编译出来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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