Page 1 of 1

Question regarding linking assembly and C

Posted: Tue Jul 10, 2007 8:05 pm
by babernat
All,

I'm trying to link two binary files one was created via nasm and the other via gcc. In the assembly file I reference the function in the C code with an underscore:

extern _main
call _main

My function in my c file is defined as

void main...

When I attempt to link the files using ld, I get the following error:

undefined reference to `_main'

The only way I have gotten this to link is by giving gcc the fno-leading-underscore and removing the underscore from my assembly.

Which I guess is fine, but I was under the impression that gcc will prepend functions with an underscore and that is why I put the underscore in there. In fact, if I compile under djgpp in windows, then I have no problems at all using the underscore. Am I doing something wrong or is this the way it was meant to be and I'm just misunderstanding the whole gcc underscore thing?

The software versions are:
GNU ld version 2.17.50.0.5 20060927 (SUSE Linux)
gcc (GCC) 4.1.2 20061115 (prerelease) (SUSE Linux)

Posted: Tue Jul 10, 2007 8:35 pm
by Kevin McGuire
You are correct. GCC should not put a underscore in front of function names by default. It has something to do with the GCC ABI for Linux. It is just standard as far as I know, unless someone else can explain it better.

Just for extra help do objdump -x <your C object file before linking> to determine how the function symbols need to be referenced. You should notice that there are no underscores like you stated above.

Posted: Tue Jul 10, 2007 8:51 pm
by babernat
That makes sense to me. I wanted to make sure I wasn't going crazy. Thanks for the tip on objdump -x that pretty much says it all.