gpt4 book ai didi

c - 如何从汇编代码中引用C程序中的全局变量?

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:57 31 4
gpt4 key购买 nike

我有一个 C 程序,我想在外部汇编文件中访问该程序的全局变量。我该怎么做呢?使用 NASM 或 FASM 汇编程序。

此处示例代码:

[niko@dev1 test]$ cat cprogram.c 
#include <stdio.h>

int array[1024];

void func_increment(int position_index);

int main() {

array[2]=4;
func_increment(2);
printf("val=%d\n",array[2]);
}
[niko@dev1 test]$ cat asmcode.S
use64

global func_increment

section .text

func_increment:
mov eax, array[position] <- how should I insert here the symbol located inside my C program
inc eax

ret

[niko@dev1 test]$

我在 C 程序中有很多类型,例如,一个声明为数组的结构类型,它大约有 32MB 长:

typedef struct buf {
char data[REQ_BUF_SIZE];
} buf_t;

我有指针、整数和很多变量类型:

char data[64] __attribute__ ((aligned (16)));
char nl[16] __attribute__ ((aligned (16)));
uint positions[32];

最佳答案

就符号而言,如果它们是全局的,您可以通过名称引用它们。根据汇编程序和环境,您可能必须在外部声明符号和/或通过在前面加上下划线来破坏它。

使用 64 位 linux 约定和 nasm 语法,您的代码可能如下所示:

extern array
global func_increment

func_increment:
; as per calling convention, position_index is in rdi
; since each item is 4 bytes, you need to scale by 4
inc dword [array + 4 * rdi]
ret

关于c - 如何从汇编代码中引用C程序中的全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143100/

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