C与asm链接和内嵌
1 内嵌汇编
1)__asm__用于指示编译器在此插入汇编语句
2)__volatile__用于告诉编译器,严禁将此处的汇编语句与其它的语句重组合优化。 即:原原本本按原来的样子处理这这里的汇编。
The format of basic inline assembly is very much straight forward. Its basic form is asm("assembly code");
Example.
asm("movl %ecx %eax"); /* moves the contents of ecx to eax */
__asm__("movb %bh (%eax)"); /*moves the byte from bh to the memory pointed by eax */
You might have noticed that here I’ve used asm
and __asm__
.
Both
are valid. We can use __asm__
if the keyword asm
conflicts with something in our program. If we have more than one instructions, we write one per line in double quotes, and also suffix a ’\n’ and ’\t’ to the instruction. This is because gcc sends each instruction as a string to as(GAS) and by using the newline/tab we send correctly formatted lines to the assembler.
2 c文件和asm文件链接(使用gnu as汇编器)
先假设c文件中有函数c_func,调用asm文件的函数asm_func,那么c中的声明为:
void c_func();
void asm_func();
而在asm中要有相应的函数和声明为,现在假设c函数使用c calling conversion。那么name mangle的时候会在名字前加上下划线变为_c_func。
所以在汇编asm和c一起链接的时候,一定要确定好c中使用的那种方式的name mangle。对应的asm中的代码为:
.text
.extern _HelloWorld
_newSleep:
.global _newSleep
call _HelloWorld
ret
.end
加了下划线是因为c编译时候有name mangle的原因。
命令为:
gcc -o sth.exe file.c file.s.