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

I am having a problem with object link files on Mac OS X. Tracking the problem, here is my worldwide C hello 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 a hello.o link to gcc and the launch of the executable

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

Now I have to use the lc or ld program for the mac linker to link the object files instead of gcc. In this case, what arguments should be passed to the ld program to run the program? A simple pass in the name of the object file, 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 in the link or architecture information that I need to specify? Thank you

+8
gcc x86-64 linker ld macos
source share
2 answers

Well, I also had this question. Yes, the cause of linker errors is that you need to pass all the magic arguments that gcc does. And an easy way to detect this is to call the -v on gcc to show all the commands that are executed during compilation. In your case, run:

 gcc hello.o -o hello -v 

... whose output on my system ends with the line:

 /usr/libexec/gcc/i686-apple-darwin9/4.2.1/collect2 -dynamic -arch i386 -macosx_version_min 10.5.8 -weak_reference_mismatches non-weak -o test -lcrt1.10.5.o -L/usr/lib/i686-apple-darwin9/4.2.1 -L/usr/lib/gcc/i686-apple-darwin9/4.2.1 -L/usr/lib/gcc/i686-apple-darwin9/4.2.1 -L/usr/lib/gcc/i686-apple-darwin9/4.2.1/../../../i686-apple-darwin9/4.2.1 -L/usr/lib/gcc/i686-apple-darwin9/4.2.1/../../.. test.o -lgcc_s.10.5 -lgcc -lSystem 

I do not know what the collect2 program collect2 , but if you pass all these arguments to ld , it should work the same way (at least on my system).

+5
source share

For reference, my full linker options

 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 
+7
source share

All Articles