NASM - The Netwide Assembler
NASM Forum => Using NASM => Topic started by: Phlip on August 08, 2005, 06:15:56 AM
-
I am trying to call a C function from asm, but it doesn't seem to be working properly...
I'm pretty sure I have everything right...
In C:
#include
int __cdecl callee(void) { return 0x12345678; }
int __cdecl inasm(void);
int main(void)
{
printf("%X", inasm());
return 0;
}
In ASM:
global _inasm
extern _callee
_inasm:
jmp .later
db "inasm()" ; so I can find it in the disassembly
.later:
mov eax, _callee
ret
I run this, and I get displayed on the screen the address of callee(), and it is correct. However if I change the mov line to
call _callee
then the program crashes with an "Illegal Operation" message!
I look in the generated exe with a disassembler, and find that the call statement is not referring to the function callee() at all! Sometimes (depending on what other things I add to the assembly) it is referring to the padding bytes after _inasm, sometimes to a point earlier in the _inasm function (causing infinite recursion), once it was referring to the ')' in the db string I put in for identification purposes...
What am I doing wrong? If I call a function defined elsewhere in the asm, it works perfectly.
FYI, I am compiling the C with mingw, here is the commands:
nasm test.asm -o test.o -f coff
gcc test.o test.c -o test.exe -Wall -std=c99
-
Hmm, if I use "-f win32" it works properly...
Still, I'm curious as to why it doesn't work with coff, particularly since it says in the assignment spec we should, quote:
"Use the nasm assembler, which can generate the necessary object file to link with that generated by
gnu compilation of C code with the invocation
nasm -f coff -o file.o file.asm"
-
The only thing I see is that Nasm's "-f coff" output format is for djgpp's variant of coff. I'm pretty sure Mingw wants "-f win32" - MS's variant of coff. The two are *almost* the same, so it seems unlikely that this is causing your problem.
I had to make a few changes to get it to compile/assemble under gcc/Linux - ELF doesn't use the underscore on externals, and my gcc doesn't seem to like __cdecl - I just deleted 'em. Works with either the "mov eax, callee" (the address looked reasonable - I didn't check it) or the "call callee" - prints 12345678 (would look better with a "\n" :)
Try it with "-f win32"... only thing I can think of...
Best,
Frank
-
Hehe! We're crossing emails...
Apparently, the book's wrong. Perhaps originally used with djgpp and converted for Mingw? (This isn't Paul Carter's book, is it? He recently added a Mingw "translation".)
Well, I'm glad you found the problem, anyway. We can shout it from the rooftops - "'-f win32' for Mingw!"
Best,
Frank