Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link compiled object file (hello.o) with ld on Mac OS X?

I got a problem with link objective files on a Mac OS X. Tracing back the problem is, here is my C hello world program

#include <stdio.h>
int main(){
    printf("Hello, world!\n");
    return 0;
}

//Compile with gcc (clang LLVM compiler on mac)

$ gcc -c hello.c

The output file is hello.o link with gcc and run the executable is

$ gcc hello.o -o hello
$ ./hello

Now, I have to use the mac linker program ld or Ld to link the the objective files instead of gcc. In this case, what arguments should I pass into the ld program in order to get the program run? A simple pass in the object file name, i.e.

$ ld hello.o

resulting in

ld: warning: -macosx_version_min not specified, assuming 10.6
Undefined symbols for architecture x86_64:
    "_printf", referenced from:
     _main in hello.o
    "start", referenced from:
    implicit entry/start for main executable
ld: symbol(s) not found for inferred architecture x86_64

So what other files that i need to include to link or architecture information that I need to specify? Thanks.

like image 235
SkyOasis Avatar asked Dec 02 '13 05:12

SkyOasis


People also ask

How object files are linked?

A shared object file holds code and data suitable to be linked in two contexts. First, the link-editor can process it with other relocatable and shared object files to create other object files. Second, the runtime linker combines it with a dynamic executable file and other shared objects to create a process image.

Does Macos use glibc?

"libc" is just a generic name for any C standard library. "glibc" is one specific implementation of that library, whereas Apple uses their own implementation for OS X, which is part of the libSystem library.

Can I compile C code on Mac?

Various compilers are available in Mac to compile C code. Mac C compilers compile C code into an executable. This executable can be run directly to run the C code. Clang and GCC(GNU Compiler Collection) are the common compilers that are used to compile C code.


1 Answers

For a reference, my complete linker options are

ld -demangle -dynamic -arch x86_64 
-macosx_version_min 10.9.0 
-o hello
-lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/5.0/lib/darwin/libclang_rt.osx.a
like image 146
SkyOasis Avatar answered Sep 28 '22 03:09

SkyOasis