Ionut Hulub
Ionut Hulub

Reputation: 6326

declaring a string in assembly

I have this assembly code that computes some prime numbers:

#include <stdio.h>

int main() {
    char format[] = "%d\t";

    _asm{
        mov ebx, 1000
        mov ecx, 1
        jmp start_while1
incrementare1:
        add ecx, 1
start_while1:
        cmp ecx, ebx
        jge end_while1
        mov edi, 2
        mov esi, 0
        jmp start_while2
incrementare2:
        add edi, 1
start_while2:
        cmp edi, ecx
        jge end_while2
        mov eax, ecx
        xor edx, edx
        div edi
        test edx, edx
        jnz incrementare2
        mov esi, 1
end_while2:
        test esi, esi
        jnz incrementare1
        push ecx
        lea ecx, format
        push ecx
        call printf
        pop ecx
        pop ecx
        jmp incrementare1
end_while1:
        nop
    }
    return 0;
}

It works fine but I would like to also declare the 'format' string in asm, not in C code. I have tried adding something like format db "%d\t", 0 but it didn't work.

Upvotes: 1

Views: 2305

Answers (2)

Michael
Michael

Reputation: 58437

If all else fails there's always the ugly way:

format_minus_1:
mov ecx,0x00096425  ; '%', 'd', '\t', '\0' in little-endian format
lea ecx,format_minus_1 + 1  ; skip past the "mov ecx" opcode
push ecx
call printf

Upvotes: 2

Dave Rager
Dave Rager

Reputation: 8150

You cannot define objects inside the _asm block with those directives. The C declaration is allocating space on the stack for you so if you want to do something like that inside the _asm block you need to manipulate the stack pointer and initialize the memory yourself:

sub esp, 4
mov [esp], '%'
mov [esp + 1], 'd'
mov [esp + 2], '\t'
mov [esp + 3], '\0'
...
push ecx
push esp + 4
call printf

Note this is one way. Not necessarily the best way. The best way being let C do your memory management for you.

Upvotes: 1

Related Questions