Notary
Notary

Reputation: 31

gcc does not include extern variables in symbol table when optimisation is used

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>

Upvotes: 1

Views: 1412

Answers (2)

Lee Duhem
Lee Duhem

Reputation: 15121

If your foo.c only (essentially) has

extern const int my_symbol;

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;
}

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

Upvotes: 3

Mahonri Moriancumer
Mahonri Moriancumer

Reputation: 6003

With `-O1' and '-O2', the compiler tries to reduce code size and execution time. One of the optimizations used to reduce the size of the resulting executable is to 'throw everything overboard' that is not required for execution. The symbol table of an executable is one of those debugging niceties that is really not required for execution; so it is excluded from the final output file.

('-O0' means "Do no optimizations").

Upvotes: 1

Related Questions