Red_A_Mountain
Red_A_Mountain

Reputation: 13

Problem linking an Assembly (AT&T) file with C program using GCC

I have my C program in 'main.c' and a function called list_equal() in 'list_equal.c'.

#include <stdlib.h>
#include "main.h"

int list_equal(const node_t *l1, const node_t *l2) {
    while (l1!=NULL && l2!=NULL) {
        if (l1->elem != l2->elem) return 0;
        l1 = l1->next;
        l2 = l2->next;
    }
    return l1==NULL && l2==NULL;
}

When I compile my program using:

$ gcc -m32 main.c list_equal.c -o main

everything worked fine and I was able to run my program './main'.

Then I translated my function in assembly code using AT&T syntax and named it "list_equal.s". Here's the code.

.globl list_equal

list_equal:

movl 4(%esp),%eax
movl 8(%esp),%ecx

L:

testl %eax,%eax
jz E
testl %ecx,%ecx
jz E
movw (%ecx),%dx
cmpw %dx,(%eax)
je F
movl $0,%eax
ret

E:

testl %eax,%eax
setz %al
testl %ecx,%ecx
setz %ah
andb %ah,%al
movsbl %al,%eax
ret

F:

movl 4(%eax),%eax
movl 4(%ecx),%ecx
jmp L

But when I try to compile my program again, this time using the assembly 'list_equal.s', with the command:

$gcc -m32 main.c list_equal.s -o main

I get this error message:

Undefined symbols for architecture i386:
  "_list_equal", referenced from:
      _test in main-bbda7f.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thank you in advance.

Informations about my gcc compiler:

$ gcc --version
Configured with: --prefix=/Applications/Xcode_9.4.1.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.1.0 (clang-902.0.39.2)
Target: x86_64-apple-darwin18.6.0
Thread model: posix
InstalledDir: /Applications/Xcode_9.4.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

Upvotes: 1

Views: 56

Answers (1)

the busybee
the busybee

Reputation: 12653

The compiler prepends an underscore character at the function name.

You can see what the compiler generates if you call it like this:

gcc -S -m32 list_equal.c -o list_equal.c.s

Without -m32 there is no extra character.

Upvotes: 1

Related Questions