user9302308
user9302308

Reputation:

How can I use an int in __asm__?

I want to use an char variable in c and add it to the assembly code.

char c = 'X';
__asm__ __volatile__("movb '"c"', %ah\n");

but when I use it it says a string literal is expected. How do I cast it? Also I am using this code to make my own os so there will be no standard libraries.

Upvotes: 0

Views: 828

Answers (1)

Martin Rosenau
Martin Rosenau

Reputation: 18503

Your inline assembler line has two problems:

1) You are using AT&T syntax. In AT&T syntax constant values use a $:

mov $'c', %ah

As far as I know a % must be written as %% when using inline assembly - similar to printf(). So a correct program would look like this:

#define c "X"
__asm__ __volatile__("movb $'" c "', %%ah\n");

2) This will only work when c is a string constant.

You'll have to use inline assembler operands if you want to use parameters. If c is a constant the following will work:

__asm__ __volatile__("movb %0, %%ah\n"::"i" (c));

This will generate the instruction movb $'x', %ah however this will only work if the compiler optimization is on so the compiler knows that c has the value 'x' here.

If c is really a variable (which can change its value) or the compiler cannot figure out that c has a constant value you'll have to do something like this:

__asm__ __volatile__("movb %0, %%ah\n"::"m" (c));

This will result in an instruction like movb 7(%rsp), %ah (or movb 3(%esp), %ah in the case of 32-bit code).

Searching for information about inline assembly in the internet I found the following page containing more information:

https://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html

Upvotes: 1

Related Questions