How to compile using nasm on MacOSX

后端 未结 3 632
灰色年华
灰色年华 2021-02-13 22:15

I am trying to compile and link my first program on Assembler. I try to compile the following code:

; %include \"stud_io.inc\"    
global _main     

section .te         


        
相关标签:
3条回答
  • 2021-02-13 22:56

    I noticed that most examples show standalone assembly programs, but it is perhaps more common for assembly to be called from C. I created a simple C program that uses a minimal nasm-assembled function like this:

    extern unsigned cpuid(unsigned n);
    
    /* ... */
            unsigned n = cpuid(1);
    

    The assembly looks like this:

    section .text
        global _cpuid
    
    _cpuid:
        push rbp
        mov rbp, rsp
        mov rax, rdi
        cpuid
        mov rax, rcx
        leave
        ret
    

    You can see the whole thing, including nasm CLI options in the makefile, here:

    https://github.com/ecashin/low/tree/master/cpuid

    It does something mildly useful by printing out the availability of some CPU-specific features. (But it does that by using CPUID without checking whether it's available. If the CPU is Intel and newer than an i486, though, that's fine.)

    The example is tested on Mac OS X Snow Leopard with the nasm from the ports collection. Removing the underscore prefix is the only change necessary for porting to Linux x86_64.

    0 讨论(0)
  • 2021-02-13 22:59

    maybe try static linking?

    ld -macosx_version_min 10.13 -e _main -static main.o
    
    0 讨论(0)
  • 2021-02-13 23:01

    I would recommend first updating your NASM.

    After that, try running this:

    nasm -f macho64 main.asm -o main.o  && ld -e _main -macosx_version_min 10.8 -arch x86_64 main.o -lSystem
    

    Notice that the new command adds JasonD's suggestion above (macho64), but also adds the -lSystem to the ld command to stop ld from throwing following error:

    ld: dynamic main executables must link with libSystem.dylib for architecture x86_64
    
    0 讨论(0)
提交回复
热议问题