qiubit
qiubit

Reputation: 4806

OS X - undefined symbols for architecture i386 when using inline assembly in C

I'm trying to compile code containing the following function:

void print_stacktrace()
{
    void *addr;
    asm("mov %0, esp;" : "=r" (addr));
}

As you can see there is some inline i386 assembly involved. The problem is, when trying to run:

clang -masm=intel -m32 test.c -o test

The compiler outputs:

Undefined symbols for architecture i386:
  "esp", referenced from:
      _print_stacktrace in test-093116.o
ld: symbol(s) not found for architecture i386
clang-3.9: error: linker command failed with exit code 1 (use -v to see invocation)

However the code compiles fine on x64 Ubuntu, so it seems problem is OS X specific. How to get this working? I can't believe Apple didn't supply i386 symbols in Xcode Developer tools package (which I have), so maybe something is misconfigured here... Any ideas?

EDIT: So it seems intel syntax is not supported on OS X by default. Is there any way to fix that?

Upvotes: 4

Views: 3021

Answers (1)

user3078414
user3078414

Reputation: 1937

Seems that -masm=intel isn't or wasn't supported in OSX default Developer Tools installation, according to man gcc, at least in the versions I'm currently using:
gcc --version
i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
The code, slightly modified, compiles and runs on OSX 10.7.x.
> gcc -m32 -masm=att -o test1 test1.c

In a newer version of OSX (10.10.x) gcc seems aliased to clang. -masm=intel also doesn't seem supported:
> clang --version
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.1.0
Thread model: posix
> clang -m32 -o test1 test1.c

#include <stdio.h>

void* print_stacktrace()
{
    void *addr;
    asm("mov %%esp, %0;" : "=r" (addr));
    return addr;
}


int main (int argc, char *argv[])
{
    printf("%p\n", print_stacktrace());
    return 0;
}

Hope this can help. This SO post may also be of relevance.

Upvotes: 1

Related Questions