How to compile/build and run Objective-C program in Ubuntu using Terminal?

Solution 1:

In Ubuntu 14.04 LTS, go ahead and install GNU objective-c compiler:

sudo apt-get install gobjc  

Verify the version:

gcc --version

must say something like:

gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
....

Install GNUStep development libraries (equivalent to Cocoa on macosx):

sudo apt-get install gnustep-devel

It should work and compile with:

gcc HelloWorld.m `gnustep-config --objc-flags` `gnustep-config --base-libs` -o HelloWorld

You should run with:

./HelloWorld

Solution 2:

I did a little research and found a solution that works for now. I'll probably post a new question to see if there is a way to shorten this. But this successfully compiles my code. Thank you to everyone who provided some help, I definitely learned some new things.

gcc -o hello hello.m \
    -I `gnustep-config --variable=GNUSTEP_SYSTEM_HEADERS` \
    -L `gnustep-config --variable=GNUSTEP_SYSTEM_LIBRARIES` \
    -lgnustep-base -fconstant-string-class=NSConstantString \
    -D_NATIVE_OBJC_EXCEPTIONS

Solution 3:

You're missing the name for executable file. So, the command should be like:

gcc -o hello helloworld.m

After compilation, type

./hello

-o hello specifies the name of the output file you wish to create once the source is compiled. (In this case the output file name is hello.) This will create an executable file (named hello) which you, then, can run directly from the terminal. If you don't use -o option while compiling, the name of the executable file will be a.out by default. Now to execute that program, you need to type

./hello

The above commands assume you are already in the location of the source files, but both the source file and target output file may also be specified as a directory. For example:

gcc -o ~/Projects/hello ~/Desktop/hello.c

will compile a C source file located on your desktop and place the executable binary in a Projects folder in your home directory. To run this executable, type;

./Projects/hello

Or you can also first go to the directory where the source file is located and run above commands. You do not need specify pathnames if you're in the same directory where your source file is.

I'm wondering why your file extension is .m instead of .c.