NASM:编译时提供常量值

NASM: Provide constant value at compile time

假设我有一些通用的 x86 NASM 代码:

%define Constant 123
mov si, Constant

问题是常量值Constant在写程序集的时候还不知道。我的意思是在汇编文件时应该提供常量的值。在我的例子中,我需要的常量取决于文本文件的大小。

如何实现?

在查看了 NASM 手册后,我没有发现汇编器的命令行选项可以满足我的要求。我的解决方案非常简单。以下脚本展示了我是如何解决这个问题的。

#!/bin/sh

# Could be replaced by any other way of getting the constant value; this gets a file's size
fileSize=`stat --printf="%s" my_file.txt`

# Write the constant definition to a temporary file
printf "%%define FILE_SIZE %s\n" $fileSize > tmp

# Append the rest to the temporary file 
cat my_asm.asm >> tmp

# Assemble the file and name the output correctly
nasm tmp -o my_asm.out

# Remove the temporary file
rm tmp