Error: 'undefined reference' in g++ but gcc succeeded

L

Lu

[jxlu@edusrv compact]$ cat main.c
extern void asm_exit(int);

int main(int argc,char *argv[])
{
asm_exit(0);
}
[jxlu@edusrv compact]$ cat asm_exit.asm
; exit() by assembly: void asm_exit(int status)
; assemble: nasm -f elf asm_exit.asm

bits 32 ; 32bit mode

section .text ; code must resides in the ".text" in gcc
global asm_exit ; declare asm_exit() as a public function

asm_exit:
mov ebp, esp ; [ebp] points return address and [ebp+4] points 1st
argument
mov ebx, [ebp+4]; read status code
mov eax, 1 ; call sys_exit()
int 0x80 ; never returns

[jxlu@edusrv compact]$ cat Makefile
CC=gcc
CPP=g++
CFLAGS=-Wall -nostartfiles -e main
MACROS=

all: main++ main

main++: main.c asm_exit.o
$(CPP) $(MACROS) $(CFLAGS) -o main++ main.c asm_exit.o

main: main.c asm_exit.o
$(CC) $(MACROS) $(CFLAGS) -o main main.c asm_exit.o

asm_exit.o: asm_exit.asm
nasm -f elf asm_exit.asm

clean:
rm -f main main++ asm_exit.o
[jxlu@edusrv compact]$ make main
nasm -f elf asm_exit.asm
gcc -Wall -nostartfiles -e main -o main main.c asm_exit.o
main.c: In function `main':
main.c:6: warning: control reaches end of non-void function
[jxlu@edusrv compact]$ ./main
[jxlu@edusrv compact]$ make main++
g++ -Wall -nostartfiles -e main -o main++ main.c asm_exit.o
/tmp/ccGG2rjn.o: In function `main':
/tmp/ccGG2rjn.o(.text+0x16): undefined reference to `asm_exit(int)'
collect2: ld returned 1 exit status
make: *** [main++] Error 1
[jxlu@edusrv compact]$

Any suggestions?

Sincerely,
Lu
 
R

Roel Schroeven

Lu said:
[jxlu@edusrv compact]$ cat main.c
extern void asm_exit(int);

extern "C" void asm_exit(int);

C++ mangles function names (so it can differentiate between functions
with the same name but a different signature), while C doesn't. The
'extern "C"' modifier tells the compiler not to mangle the name of that
function.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top