Objective-c – Compiling multiple Objective-C files on the command line with clang

cclangobjective c

Hopefully simple question. I'm trying to learn basic Objective-C compiling from the command line, with clang. I understand that Xcode is a better solution for complex projects and I plan on moving to it soon, but I personally feel I understand a language better if I can compile it manually in a terminal, and for small introductory programming projects I find it less of a hassle to compile in a terminal than having to start a new project.

So the question is: how do I compile an Objective-C program that consists of multiple files (from the command line)? (I'm trying to do the fraction program from chapter 7 of Kochan's textbook, with a main.m and Fraction.m file that both #import "Fraction.h", and a Fraction.h file that imports the Foundation framework.) To compile a single file I use something like

clang -fobjc-arc main.m -o prog1

But if I type that and I want to include files other than main.m in the project, I get errors including:

ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

If I try to add the additional files to the command as arguments, like

clang -fobjc-arc main.m Fraction.h Fraction.m -o prog1

then I get

clang: error: cannot specify -o when generating multiple output files

And if I then remove the -o argument like

clang -fobjc-arc main.m Fraction.h Fraction.m

then I get a giant pile of errors all referring to the foundation framework, eventually ending in "fatal error: too many errors emitted, stopping now".

How do I do this and make it work? Or do I need to just suck it up and use Xcode as soon as more than one file is involved?

Best Answer

Only the implementation files (*.m) are compiled, not the interface/include files, so this should work:

clang -fobjc-arc main.m Fraction.m -o prog1

The strange error message "generating multiple output files" is probably caused by the fact that clang can also compile header files to "precompiled header files".