简体   繁体   中英

Integrate NASM to a compiler written in C

I have a C program that generates nasm assembly. How can I assemble it with nasm and then link it with ld to generate the final executable?

The easiest thing would be to just pipe the compiler's output into nasm, but I wanted the process to be simple for the user: just type compiler myfile and get an executable. Even if I would go through that easy route, nasm does not seem to accept files from stdin; you have to specify them as arguments.

So what I have so far is: output the assembly to stdout, create a pipe between the main process' stdout and a child process' stdin, and this process would be a call to nasm /dev/stdin . What am I doing wrong here?

In fact, your suggested procedure will not work, because nasm reads its input file twice (unless you suppress the preprocessor pass with the -a flag).

So it would be necessary that /dev/stdin be an ordinary file, not a pipe. And if it were going to be an ordinary file, it might as well have a name.

So just write your output to a temporary file, call nasm on that file, and then delete it.

This is not an answer, but a suggestion of how to implement such a helper script:

#!/bin/sh
SrcDir="$(mktemp -d)" || exit 1
trap "rm -rf '$SrcDir'" EXIT

cat > "$SrcDir/source.asm"
nasm "$@" "$SrcDir/source.asm"

The mktemp -d creates a new temporary directory. The trap removes that directory and all its contents, when the shell exits. Note that because the command is in doublequotes, the path to the directory is evaluated when the trap is set. If one were to change SrcDir later, it would not affect the trap at all; the original temporary directory gets used and deleted.

Any parameters to the script will be passed to nasm as-is (due to "$@" ), with the path to the temporary file as the final parameter.

This pattern is useful in all kinds of situations, because the temporary directory will get removed even if the script is aborted (due to say Ctrl + C or because of a bug in the script).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM