How to write multiline inline assembly code in GCC C++?

送分小仙女□ 提交于 2019-12-01 00:42:59

问题


This does not look too friendly:

__asm("command 1"
      "command 2"
      "command 3");

Do I really have to put a doublequote around every line?

Also... since multiline string literals do not work in GCC, I could not cheat with that either.


回答1:


I always find some examples on Internet that the guy manually insert a tab and new-line instead of \t and \n, however it doesn't work for me. Not very sure if your example even compile.. but this is how I do:

VERY ugly way:

asm("xor %eax,%eax");
asm("mov $0x7c802446, %ebx");
asm("mov $500, %ax");
asm("push %eax");
asm("call *%ebx");

Or this less ugly one:

asm("xor %eax,%eax         \t\n\
    mov $0x7c802446, %ebx  \t\n\
    mov $1000, %ax         \t\n\
    push %eax              \t\n\
    call *%ebx             \t\n\
    ");



回答2:


C++ multiline string literals

Interesting how this question pointed me to the answer:

main.cpp

#include <cassert>
#include <cinttypes>

int main() {
    uint64_t io = 0;
    __asm__ (
        R"(
incq %0
incq %0
)"
        : "+m" (io)
        :
        :
    );
    assert(io == 2);
}

Compile and run:

g++ -o main -pedantic -std=c++11 -Wall -Wextra main.cpp
./main

See also: C++ multiline string literal

GCC also adds the same syntax as a C extension, you just have to use -std=gnu99 instead of -std=c99:

main.c

#include <assert.h>
#include <inttypes.h>

int main(void) {
    uint64_t io = 0;
    __asm__ (
        R"(
incq %0
incq %0
)"
        : "+m" (io)
        :
        :
    );
    assert(io == 2);
}

Compile and run:

gcc -o main -pedantic -std=gnu99 -Wall -Wextra main.c
./main

See also: How to split a string literal across multiple lines in C / Objective-C?

One downside of this method is that I don't see how to add C preprocessor macros in the assembly, since they are not expanded inside of strings, see also: Multi line inline assembly macro with strings

Tested on Ubuntu 16.04, GCC 6.4.0, binutils 2.26.1.

.incbin

This GNU GAS directive is another thing that should be in your radar if you are going to use large chunks of assembly: Embedding resources in executable using GCC

The assembly will be in a separate file, so it is not a direct answer, but it is still worth knowing about.



来源:https://stackoverflow.com/questions/3666013/how-to-write-multiline-inline-assembly-code-in-gcc-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!