我试图了解如何在 C 中嵌入汇编语言(在 x86_64 架构上使用 gcc)。我编写这个程序是为了增加单个变量的值。但我得到的输出是垃圾值。和想法为什么?
#include <stdio.h>
int main(void) {
int x;
x = 4;
asm("incl %0": "=r"(x): "r0"(x));
printf("%d", x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢
更新该程序在 gcc 4.8.3 上给出了预期结果,但在 gcc 4.6.3 上没有给出预期结果。我粘贴非工作代码的汇编输出:
.file "abc.c"
.section .rodata
.LC0:
.string "%d"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
pushq %rbx
subq $24, %rsp
movl $4, -20(%rbp)
movl -20(%rbp), %eax
incl %edx
movl %edx, %ebx
.cfi_offset 3, …Run Code Online (Sandbox Code Playgroud) 我已经在程序中创建了一个集合向量,我需要遍历每个集合。如果在集合中找到特定元素,则需要向向量添加一个新集合。但是,一旦我的数组的计数器到达后来插入的元素(在循环内),这就会给我带来分段错误。在以下代码中,打开list.push_back(cS)会给我带来分段错误。
int main(void) {
set<int> cS;
vector<set<int> > list;
cS.insert(1);
list.push_back(cS);
cS.insert(2);
list.push_back(cS);
for (int ctr = 0; ctr < list.size(); ctr++)
{
for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
{
if (*itr == 1 || *itr == 2)
{
cS.clear();
cS.insert(3);
//list.push_back(cS);
}
}
}
for (int ctr = 0; ctr < list.size(); ctr++)
{
for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
{
cout << *itr << endl;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果有人能解释为什么会给出错误(以gcc为单位),我将不胜感激。
感谢您浏览我的帖子。
我正在尝试编写以下形式的函数:
void swap(int *a, int *b);
在 x86-64 汇编中。
[section .text]
global swap ;
swap: mov ecx, [esp+8] ; copy parameter a to ecx
mov edx, [esp+16] ; copy parameter b to edx
mov eax, [ecx] ; copy a into eax
xchg eax, [edx] ; exchange eax with b
mov [ecx], eax;
ret;
Run Code Online (Sandbox Code Playgroud)
我使用以下命令在 Linux 上编译它:
Run Code Online (Sandbox Code Playgroud)nasm -f elf64 swap.asm
它编译没有任何错误。主要文件如下:
#include <stdio.h>
extern void swap(int *a,int *b);
int main(){
int a = 10, int b = 20;
swap(&a,&b);
printf("a …Run Code Online (Sandbox Code Playgroud)