在C的装配中使用标签

Ken*_*rey 13 c assembly gcc nasm

我只需要一种方法来加载标签的地址,例如MyLabel:例如'src.asm'到例如'src.c'中的变量.(这些文件将链接在一起)我使用gcc和nasm来组装这些文件.如何加载标签地址?

ugh*_*fhw 17

这有两个步骤.首先,必须使用global指令从程序集文件中将标签导出为全局.

global MyLabel

MyLabel: dd 1234    ; data or code, in whatever section.  It doesn't matter.
Run Code Online (Sandbox Code Playgroud)

接下来,您必须在C中将标签声明为外部.您可以在使用它的代码中或在标头中执行此操作.

// It doesn't matter, and can be plain void,
// but prefer giving it a C type that matches what you put there with asm
extern void MyLabel(void);            // The label is code, even if not actually a function
extern const uint32_t MyLabel[];      // The label is data
// *not*  extern long *MyLabel, unless the memory at MyLabel *holds* a pointer.
Run Code Online (Sandbox Code Playgroud)

最后,您获得C中标签的地址,就像获取任何变量的地址一样.

doSomethingWith( &MyLabel );
Run Code Online (Sandbox Code Playgroud)

请注意,某些编译器会在C变量和函数名称的开头添加下划线.例如,GCC在Mac OS X上执行此操作,但不在Linux上执行此操作.我不知道其他平台/编译器.为了安全起见,可以asm在变量声明中添加一个语句,告诉GCC变量的程序集名称是什么.

extern uint8_t MyLabel asm("MyLabel");
Run Code Online (Sandbox Code Playgroud)

  • 我认为`void*`可能是你能给它的最危险的类型(因为它很容易忘记`&`).通常选择`char`类型用于任意符号,但`void`也应该有效. (2认同)