在 C 中使用程序集全局变量

Using Assembly global variable in C

正在尝试在 a.s 中编译此代码:

section .bss
global _start
global TestVar
TestVar:    RESB 4

section .text
extern main

_start:

以及 b.c 中的代码:

extern int TestVar;

void test2(int x, int y)
    {
      int z = TestVar;
      x = z + y;
      y = 1;
    }

int main(int argc, char **argv) {
      return 0;
    }

使用此生成文件:

all:    test

test:   a.o b.o
    ld -melf_i386 a.o b.o -o test
a.o:    a.s
    nasm -f elf  a.s -o a.o
b.o:    b.c
    gcc -m32 -Wall -g b.c -o b.o

.PHONY: clean
clean: 
    rm -f *.o test

运行 makefile 生成:

m@m-All-Series:~/testFolder$ make
nasm -f elf  a.s -o a.o
gcc -m32 -Wall -g b.c -o b.o
/tmp/ccjymll2.o: In function `test2':
/home/m/testFolder/b.c:5: undefined reference to `TestVar'
collect2: error: ld returned 1 exit status
makefile:9: recipe for target 'b.o' failed
make: *** [b.o] Error 1

我做错了什么? 另外,main 在那里只是因为如果它不存在 - 编译器说在 crt1.o 的 _start 中有一个对 main 的未定义引用,将永远不会调用 main,只有 test2,我不知道这是否重要所以我也包含了该信息。

如果要将 C 源代码编译成目标文件,则必须使用编译器的 -c 选项。没有它,gcc 会尝试继续链接,这不是您想要的。例如

b.o: b.c
       gcc -c -m32 -Wall -g b.c

应该会让你更进一步。