Pony
Pony

Reputation: 129

Compiling object c (.m) file to an object file(.o) in osx

Thanks for reviewing the problem. There is an object c file called try.m, and I complie it to an object file try.o with the command:

gcc -c try.m -o try.o -framework Foundation

the try.h is

int print_word( void );

The try.m is:

#include "try.h" 
#import <Foundation/Foundation.h>

int print_word( void )
{
  NSLog (@"say hello");
  return 0;
}

Additionly, there is a main.c file, which contain the main() function, and it looks:

#include <stdio.h>
#include "try.h"

int main()
{
   printf( "This is main\n");
}

I compile main.c to main.o by the following command:

gcc -o main.o -c main.c

Then, I link the main.o and try.o to form the executable file main:

gcc  -o main main.o try.o

After these steps, the following errors happened: enter image description here

The errors are:

Undefined symbols for architecture x86_64:
"_NSLog", referenced from:
    _print_word in try.o
ld: symbol(s) not found for architecture x86_64    
clang: error: linker command failed with exit code 1 (use -v to see invocation)

How could these errors be solved?

Upvotes: 1

Views: 275

Answers (1)

EricS
EricS

Reputation: 9768

You need to link against the Foundation framework. You can do it all in a single command: gcc main.c try.m -framework Foundation.

Upvotes: 2

Related Questions