skgbanga
skgbanga

Reputation: 2667

inline assembly in C++ function with return statement

Consider this code:

#include <cstdio>

int get_value() { asm("movl $254, %eax"); }

int main() { printf("%d\n", get_value()); }

Now if one compiles this code with g++ main.cpp, one gets a compiler warning (but the code still compiles):

main.cpp: In function ‘int get_value()’:
main.cpp:3:43: warning: no return statement in function returning non-void [-Wreturn-type]
    3 | int get_value() { asm("movl $254, %eax"); }
      |                                    

As this answer says that if a compiler generates a binary with the above code, all bets are off. (no return statement from a function with return type int)

Indeed, when one compiles this code with optimization turned on g++ -O3 main.cpp, this program immediately segfaults.

So my question is how can one return from inline assembly within a c++ function that is conformant with C++, and one doesn't get this warning, and the code works fine.

Upvotes: 3

Views: 1698

Answers (1)

Gem Taylor
Gem Taylor

Reputation: 5635

I believe what you have to do is declare a dummy variable, and use the gcc extended syntax to output that variable, and then you can return that variable. The optimiser should strip both assignents out.

It is sort-of explained in https://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html#s5, and might look like this:

#include <cstdio>

int get_value() {
  int b;
  asm("movl $254, %0;"
      : "=r"(b)
      );
  return b;
}

int main() {
  printf("%d\n", get_value());
}

Upvotes: 4

Related Questions