使用优化时,gcc不在符号表中包含外部变量 [英] gcc does not include extern variables in symbol table when optimisation is used

查看:358
本文介绍了使用优化时,gcc不在符号表中包含外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序包含许多外部定义的变量。当我使用-O0标志进行编译时,我在符号表中看到它们,但在使用-O1或-O2时看不到它们。如何强制编译器导出它们?

My program contains many externally defined variables. When I compile it with -O0 flag, I see them in the symbol table, but not when I use -O1 or -O2. How can I force the compiler to export them?

foo.c:
    extern const int my_symbol;

    void my_fn()
    {
        void *x = &my_symbol;
        // but x is not used, that's probably why it is optimised out
    }

nm foo.o (with O0):
    U my_symbol

nm foo.o (with O2):
    <my_symbol absent>


推荐答案

如果您的 foo.c 只有(本质上)有

If your foo.c only (essentially) has

extern const int my_symbol;

然后用 -O1 -O2 ,该符号将被优化。但是,如果您在 foo.c 中使用该符号,例如

then compile it with -O1 or -O2, that symbol will be optimized out. However, if you use that symbol in foo.c, for example

extern const int my_symbol;
extern int my_flag;

void foo(void)
{
    if (my_symbol)
        my_flag = 1;
}

所有这些符号都将存在于 foo.o ,即使你用 -O1 -O2 来编译它。

All of those symbols will exist in foo.o even if you compile it with -O1 or -O2.

这篇关于使用优化时,gcc不在符号表中包含外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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