Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems when compiling Objective C with Clang (Ubuntu)

I'm learning Objective-C language. Since I don't have a Mac, I'm compiling and running my code within Ubuntu 11.04 platform.

Until now, I was using gcc to compile. I've installed GNUStep and all was working. But then I started to try some Objective-C 2.0 features, like @property and @synthesize, that gcc does not allow.

So I tried to compile the code with Clang, but it seems that it is not correctly linking my code with the GNUStep libraries, not even with a simple Hello world program.

For example, if I compile the following code:

#import <Foundation/Foundation.h>

int main(void) {
  NSLog(@"Hello world!");
  return 0;
}

The output of the compiler is:

/tmp/cc-dHZIp1.o: In function `main':
test.m:(.text+0x1f): undefined reference to `NSLog'
/tmp/cc-dHZIp1.o: In function `.objc_load_function':
test.m:(.text+0x3c): undefined reference to `__objc_exec_class'
collect2: ld returned 1 exit status
clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)

The command I'm using to compile is

clang -I /usr/include/GNUstep/ test.m -o test

with the -I directive to include the GNUStep libraries (otherwise, Clang is not able to find Foundation.h).

I've googled my problem, and visited both GNUStep and Clang web pages, but I haven't found a solution to it. So any help will be appreciated.

Thanks!

like image 646
eze.scaruli Avatar asked Feb 18 '12 00:02

eze.scaruli


2 Answers

The problem was that the library gnustep-base was not being used by the linker. So the solution to this was using the option -Xlinker, that sends arguments to the linker used by clang:

clang -I /usr/include/GNUstep/ -Xlinker -lgnustep-base test.m -o test

The statement "-X linker -lgnustep-base" made the magic. However, I had problems with this command related to the class that represents a string in Objective-C:

./test: Uncaught exception NSInvalidArgumentException, reason: GSFFIInvocation:
Class 'NXConstantString'(instance) does not respond to forwardInvocation: for
'hasSuffix:'

I could solve it adding the argument "-fconstant-string-class=NSConstantString":

clang -I /usr/include/GNUstep/ -fconstant-string-class=NSConstantString \
-Xlinker -lgnustep-base test.m -o test

In addition, I've tried with some Objective-C 2.0 pieces of code and it seems to work.

Thank you for the help!

like image 95
eze.scaruli Avatar answered Nov 25 '22 14:11

eze.scaruli


You can try gcc compiler:
First of all install GNU Objective-C Runtime: sudo apt-get install gobjc
then compile: gcc -o hello hello.m -Wall -lobjc

like image 28
0xDE4E15B Avatar answered Nov 25 '22 14:11

0xDE4E15B