What is the syntax for directives in gcc asm command?

北慕城南 提交于 2019-12-25 19:02:35

问题


I'm trying to use .ascii directive in the gcc extended asm command but I keep getting compiler errors. What is the exact syntax for directives inside extended asm?

I tried the following options but none of the worked:

asm ("NOP;"
".ASCII ""ABC"""
);

I got "Error: junk at end of line, first unrecognized character is `/'"

asm ("NOP;"
".ASCII "ABC""
);

I got Error: junk at end of line, first unrecognized character is `/'"

asm ("NOP;"
.ASCII "ABC"
);

I got "error: expected ‘:’ or ‘)’ before ‘/’ token"


回答1:


The syntax for directives inside the asm is identical to writing GNU Assembler, so you can reference the GNU Assembler manual for the relevant syntax.

Example:

#include <stdio.h>
int
main (void)
{
  char *string;
  asm (".pushsection .rodata\n"
"0:\n"
"   .ascii \"Testing 1 2 3!\"\n"
"   .popsection\n"
"   mov $0b, %0\n":"=rm" (string));
  puts (string);
}

In the example we use an extended asm to copy the address of a string to a char * and then pass that to puts to print the string.

The string needs to be placed into the appropriate linker section, not just added to the current (usually the code section i.e. .text). So you begin by pushing the section you want the string stored to into the assembler's section stack. In this example I give it's the read only data section (.rodata) where most strings live. Then you pop the section off the section stack to get back to whatever section the compiler left you in, and do your operation with the string address. The trick is to use a local label like 0 to reference the string and let the assembler and linker compute the offset for you. This may require more work if you're PIE or PIC depending on how much more complicated your references become or if they require relocations.



来源:https://stackoverflow.com/questions/36091646/what-is-the-syntax-for-directives-in-gcc-asm-command

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