gpt4 book ai didi

c - 理解c中的汇编代码

转载 作者:太空狗 更新时间:2023-10-29 17:12:26 28 4
gpt4 key购买 nike

我正在阅读一些嵌入了一些汇编代码的 C 代码。我知道 __asm__ 是运行汇编代码的语句,但是 __asm__ 在下面的代码中做了什么?根据输出(即 r = 16),似乎 __asm__ 不会影响变量 r。不是吗?

#include <stdio.h>
static void foo()
{
static volatile unsigned int r __asm__ ("0x0019");
r |= 1 << 4;

printf("foo: %u\n", r);
}

平台:OSX Yosemite 上的 Apple LLVM 版本 6.0 (clang-600.0.56)(基于 LLVM 3.5svn)

最佳答案

严格来说,您的“asm”片段只是加载一个常量 (0x0019)。

这是一个 32 位示例:

#include <stdio.h>
static void foo()
{
static volatile unsigned int r __asm__ ("0x0019");
static volatile unsigned int s __asm__ ("0x1122");
static volatile unsigned int t = 0x3344;
printf("foo: %u %u %u\n", r, s, t);
}

gcc -O0 -S x.c

cat x.c
.file "x.c"
.data
.align 4
.type t.1781, @object
.size t.1781, 4
t.1781:
.long 13124 # Note: 13124 decimal == 0x3344 hex
.local 0x1122
.comm 0x1122,4,4
.local 0x0019
.comm 0x0019,4,4
.section .rodata
.LC0:
.string "foo: %u %u %u\n"
.text
.type foo, @function
foo:
pushl %ebp
movl %esp, %ebp
subl $24, %esp
movl t.1781, %eax
movl 0x1122, %edx
movl 0x0019, %ecx
movl %eax, 12(%esp)
movl %edx, 8(%esp)
movl %ecx, 4(%esp)
movl $.LC0, (%esp)
call printf
leave
ret

附言:“asm”语法适用于所有基于 gcc 的编译器。

附:我绝对鼓励您在任何地方尝试汇编:嵌入式系统、Ubuntu、Mac OSX - 任何您喜欢的东西。

这是一本很棒的书。它是关于 Linux 的,但它在很大程度上也适用于您的 OSX:

Programming from the Ground Up, Jonathan Bartlett

还有:

https://www.hackerschool.com/blog/7-understanding-c-by-learning-assembly

http://fabiensanglard.net/macosxassembly/

附:x86 汇编语法有两种变体:“Intel”和“ATT”语法。 Gcc 使用 ATT。 ATT 语法也适用于 GCC 支持的任何其他架构(MIPS、PPC 等)。我鼓励您从 ATT 语法(“gcc/gas”)开始,而不是 Intel(“nasm”)。

关于c - 理解c中的汇编代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671120/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com