GCC NOPs being compiled away

Rushyo picture Rushyo · Dec 31, 2010 · Viewed 10.8k times · Source

Venturing out of my usual VC++ realm into the world of GCC (via MINGW32). Trying to create a Windows PE that consists largely of NOPs, ala:

for(i = 0; i < 1000; i++)
{
    asm("nop");
}

But either I'm using the wrong syntax or the compiler is optimising through them because those NOPs don't survive the compilation process.

I'm using the -O0 flag, otherwise defaults. Any ideas on how I can coax the compiler into leaving the NOPs intact?

Answer

Nate Eldredge picture Nate Eldredge · Oct 23, 2020

A convenient way to get 1000 inline nops is to use the .rept directive of the GNU assembler:

void thousand_nops(void) {
    asm(".rept 1000 ; nop ; .endr");
}

Try on godbolt.