Arc676
Arc676

Reputation: 4465

Compiling *.mm with GCC

I'm making a very simple Objective-C/C program in a .mm file but I don't know how to link the Objective-C libraries/frameworks. I only need the Foundation framework. How can I do this? I don't want to do this in Xcode because Xcode always creates an entire folder with project files and then buries the product in a hard-to-find folder and I feel that it is a lot of memory used for a one-file program.

Code:

#include <stdio.h>
#import <Foundation/Foundation.h>

NSString* charToNSString(char * c){
    return [NSString stringWithUTF8String:c];
}

const char* NSStringToChar(NSString *str){
    return [str UTF8String];
}

int main(int argc, char * argv[]){
    return 0;
}

Compiling: gcc file.mm

Output:

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_NSString", referenced from:
      objc-class-ref in file-4bd3e4.o
  "_objc_msgSend", referenced from:
      charToNSString(char*) in file-4bd3e4.o
      NSStringToChar(NSString*) in file-4bd3e4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Upvotes: 3

Views: 1850

Answers (1)

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 40018

$ gcc -framework Foundation main.mm

Although above command works perfectly, but I suggest you to create Makefile

$vim Makefile

paste the content below

CC=gcc

FRAMEWORKS:= -framework Foundation

SOURCE=main.mm

OUT=-o main

all:
        $(CC) $(SOURCE) $(FRAMEWORKS) $(OUT)
#   ^ this is a tab not spaces, if you give spaces here it will through error :*** missing separator

then run

$ make

Just look at this simple tutorial about Makefile

Upvotes: 7

Related Questions