2016-02-02 70 views
0

我有一個C程序,我想在外部程序集文件中訪問這個程序的全局變量。我該怎麼做呢?使用NASM或FASM彙編器。如何從彙編代碼引用C程序中的全局變量?

樣本代碼在這裏:

[[email protected] 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]); 
} 
[[email protected] 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 

[[email protected] 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]; 
+0

我已經編輯添加彙編類型,我可以使用NASM或FASM – Nulik

+0

呀'nasm'確實需要你聲明'extern數組'。 – Jester

+0

我已閱讀文檔,但文檔指定你必須把變量的大小,但我不知道如何做到這一點與數組,我應該把數組的長度或指針? – Nulik

回答

4

只要符號去,如果它們是gl你可以通過名字引用它們。根據彙編程序和環境的不同,您可能需要在外部聲明符號並/或通過預先加下劃線來對其進行修改。

使用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 
+0

thankis很多! – Nulik