4

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?

qiubit
  • 4,708
  • 6
  • 23
  • 37

1 Answers1

1

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.

Community
  • 1
  • 1
user3078414
  • 1,942
  • 2
  • 16
  • 24
  • No need to use `-masm=att` as [ATT syntax](https://en.wikibooks.org/wiki/X86_Assembly/GAS_Syntax) is the default for _GCC_ – Michael Petch May 20 '16 at 21:36
  • That's a good answer, but I'm wondering if there's any way of enabling intel syntax on OS X. – qiubit May 21 '16 at 08:17
  • You probably can't enable what isn't there. Just try ` -masm=intel` and see what you'll get. Also read the manual. Yet, there is a chance, as @Michael Petch stated in his comment, that a _macports_ or _homebrew_ versions of gcc may support `intel` syntax. Probably some commercial compilers such as `intel` C compiler also do. – user3078414 May 21 '16 at 08:24
  • Please, also take a look at [this SO post](http://stackoverflow.com/questions/199966/how-do-you-use-gcc-to-generate-assembly-code-in-intel-syntax). – user3078414 May 21 '16 at 08:52
  • OK it seems clang doesn't support intel syntax (bug?) and gcc doesn't support intel syntax on Darwin, so it seems there is no simple way to enable that... – qiubit May 21 '16 at 12:05