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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)