Question

Is there a way to instruct g++ or clang not to compile out variables that are not being used in the code? I know that most compilers would compile out parts of the code that do not affect the final output. For debugging reasons, I wanted to know if there is a way to disable this?

Was it helpful?

Solution

Yes. In gcc (and probably clang, too) you can compile with -O0. This will disable all optimizations. You can also use -Og, which should not remove variables. This flag turns on only the "debugger-friendly" optimizations.

OTHER TIPS

Simply declare the variable volatile. This has the advantage of working on any compiler without the need for compiler specific extensions or command line options - it also allows you to be specific about which variables get this treatment. If you want to be able to remove the volatile for release builds you could use the following:

#if defined NDEBUG
    #define DEBUG_VOLATILE
#else
    #define DEBUG_VOLATILE volatile
#endif

Then declarations such as:

DEBUG_VOLATILE debug_var = 0 ;

will be volatile only in debug builds.

Perhaps:

   int foobar __attribute__((used));

The documentation http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html says (emphasis added):

This attribute, attached to a variable with the[sic] static storage, means that the variable must be emitted even if it appears that the variable is not referenced.

Update 1: Perhaps this is a https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem That is, what is the problem you are actually trying to resolve?

Anyway, as dma points out in a comment, this solution suffers because "anything added to the code is going to be harder to remove for non-debugging builds". Agreed.

Update 2: Compiling this 4-line file with -s:

int                              foo1 = 111;
static int                       foo2 = 222;
static int volatile              foo3 = 333;
static int __attribute__((used)) foo4 = 444;

gives (abridged):

.globl foo1
    .data
foo1:
    .long   111
foo4:
    .long   444

That is, the variable foo3, using Clifford's suggestion of volatile, is compiled out, while foo4 is kept. (gcc 4.1.2)

But, on the other hand, compiling:

void bar(void) {
    int                        bar2 = 222;
    int volatile               bar3 = 333;
    int __attribute__ ((used)) bar4 = 444;
}

gives:

warning: 'used' attribute ignored

and:

movl    $333, -4(%ebp)

So this is the reverse: volatile works and __attribute__ ((used)) doesn't (perhaps expected, since bar4 is not static).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top