Home > Software engineering >  How to use x64 assembly with C on windows?
How to use x64 assembly with C on windows?

Time:06-03

cpp.cpp:

#include <iostream>

extern "C" int returnnum();

int main() { std::cout << returnnum() << "\n"; }

asm.asm:

segment .text
global _returnnum
_returnnum:
    mov rax, 420
    ret

First, I compile the assembly file with nasm -f win64 asm.asm.

Then, I compile the C file with g cpp.cpp asm.obj.

But this gives me an error:

asm.obj: file not recognized: File format not recognized
collect2.exe: error: ld returned 1 exit status

I know that I can change rax to eax and compile with -f win32 and it'll work, but I want a 64-bit application. Is there any way I can do this?

If this is helpful:

g --version: g (MinGW.org GCC-6.3.0-1) 6.3.0
nasm --version: NASM version 2.15rc12 compiled on Jun 26 2020

CodePudding user response:

Based on your information from the comments and your g --version output, it looks like you installed plain MinGW (which is purely 32 bit, and works just fine if you only need to build 32 bit executables since Windows supports running 32 bit executables on a 64 bit OS) rather than MinGW-W64, the fork with native support for 64 bit Windows.

You'll need to switch if you want to build true 64 bit executables.

  • Related