markmb
markmb

Reputation: 892

Use preprocessor output as inline assembly

I can't find the way to mix preprocessor and inline assembly, and I can't find any solution on Google.

Imagine you have this constant:

(Dummy code to simplify)

#define SOME_ASM \
    .short 0x0000; \
    .short 0x0000; \
    movw %eax, %ebx; \

In an assembly file, I could do:

SOME_ASM
or      %cx, %cx
jnz     1f
or      %dx, %dx
jnz     1f
mov     %ax, %cx
mov     %bx, %dx

And it worked. But now I'm doing a new and improved version of the ASM code, and I'm doing it in C

How can I do something like this in C without modifying the constant:

asm(
  SOME_ASM
  "or       %cx, %cx\n"
  "jnz      1f\n"
  "or       %dx, %dx\n"
  "jnz      1f\n"
  "mov      %ax, %cx\n"
  "mov      %bx, %dx\n"
);

To avoid replicating code and constants

Upvotes: 0

Views: 245

Answers (1)

Jester
Jester

Reputation: 58762

The asm block is just a string, so use a string macro. Also reconsider if you really need inline asm.

#define SOME_ASM \
    ".short 0x0000;" \
    ".short 0x0000;" \
    "movw %ax, %bx;"

void foo()
{
asm(
  SOME_ASM
  "or       %cx, %cx\n"
  "jnz      1f\n"
  "or       %dx, %dx\n"
  "jnz      1f\n"
  "mov      %ax, %cx\n"
  "1:\n"
  "mov      %bx, %dx\n"
);
}

Upvotes: 3

Related Questions