gatieme
gatieme

Reputation: 105

dead code remover adbout gcc -O and higher

I have written a simple code like this

#include <stdlib.h>
#include <stdio.h>

//#define CONFIG_TARGET_X86_64

#ifdef CONFIG_TARGET_X86_64
static void A( )
{
    printf("A\n");
}
#else
void A( );
#endif

static void B( )
{
    printf("B\n");
}


static int xx( )
{
#ifdef CONFIG_TARGET_X86_64
  return 1;
#else
  return 0;
#endif
}

int main(void)
{
  if (xx( ))   /* define CONFIG_TARGET_X86_64 */
    A( );
  else
    B( );
}

If we don't define the CONFIG_TARGET_X86_64, xx( ) will always return FALSE, so functiopn A which is only declared, but not implemented will never be called(dead code).

compile it with gcc -O0

/tmp/cctSpgGk.o: In function `main':
1.c:(.text+0x34): undefined reference to `A'
collect2: error: ld returned 1 exit status

But it can be compiled by -O1 or higher.

use GCC V6.1.0

It seems that one of the optimization options in the -O1 option eliminates the dead code, I have seen the optimize doccument about GCC

https://gcc.gnu.org/onlinedocs/gcc-6.4.0/gcc/Optimize-Options.html

but I can't find it.

So I just want to compile this code under the -O0 option, Is it possible ? Are there some optimization flags help me to do this?

Thanks

Upvotes: 1

Views: 96

Answers (2)

Florian Weimer
Florian Weimer

Reputation: 33719

You can declare A as weak:

void A (void) __attribute__ ((weak));

Then the linker will ignore the undefined symbol reference, but a call to this function will lead to a crash.

Upvotes: 0

tadman
tadman

Reputation: 211560

What's worth noting here is this declares a method signature:

void A( );

Where this declares a method implementation:

void A( ) { };

There is a huge difference between these two.

If you're referencing a function with a call you need to implement it. The compiler will decide if it'll optimize that function call away or not depending on other factors, but it'll need to know what that function does, not just how it's called.

Upvotes: 1

Related Questions