---
title: "命令行编译运行Objective－C程序"
author: "alexgreenbar"
date: "2010-08-12T10:42:03Z"
tags: []
categories: ["非技术"]
slug: "objective-c"
draft: false
lastmod: "2010-08-12T10:42:03Z"
id: 735243
url: "https://codewins.iteye.com/blog/735243"
---

本来Mac上写Objective－C程序有非常好的XCode集成开发环境可以用，但不幸的是XCode 3.2后不支持Foundation类型的项目类型了，没办法，只好尝试在命令行手工进行。

 

hello.m 如下：

 

```
#import <Foundation/Foundation.h>

int main(int argc, const char *argv[]) {
  NSLog (@"hello, objective-c!");
  return 0;
}
```

 

那用什么编译链接呢？其实Mac本身用的也是gcc suite， gcc支持三种C语言的变种：C／C＋＋／Objective－C。

 

尝试＃1： 用gcc直接编译链接

```
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ gcc hello.m 
Undefined symbols:
  "___CFConstantStringClassReference", referenced from:
      cfstring=hello, objective-c! in cccGGqYO.o
  "_NSLog", referenced from:
      _main in cccGGqYO.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
```

出错了，好像是链接的问题，但是第一次写Objective-C程序，语法难道没有问题吗？

 

尝试＃2：用gcc先编译再链接

```
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ gcc -c hello.m 
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ ls
hello.m	hello.o
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ gcc hello.o
Undefined symbols:
  "___CFConstantStringClassReference", referenced from:
      cfstring=hello, objective-c! in hello.o
  "_NSLog", referenced from:
      _main in hello.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
```

 哈哈，编译没有问题，看来问题出再链接上，可是该用那个系统库呢，NSLog()对象在那个动态链接库里呢？去/usr/lib里找找：

```
Alex-Chens-MacBook-Pro:lib achen$ ls libobjc.
libobjc.A.dylib  libobjc.dylib
```

 嗯，估计是libobjc.dylib，那就链链吧：

```
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ gcc hello.o -lobjc
Undefined symbols:
  "___CFConstantStringClassReference", referenced from:
      cfstring=hello, objective-c! in hello.o
  "_NSLog", referenced from:
      _main in hello.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
```

奶奶地，不行呀，难道是gcc找不到库？加个路径试试：

```
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ gcc hello.o -lobjc -L/usr/lib
Undefined symbols:
  "___CFConstantStringClassReference", referenced from:
      cfstring=hello, objective-c! in hello.o
  "_NSLog", referenced from:
      _main in hello.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
```

 还是不行，放弃？

 

尝试#3: man gcc, 找出问题

```
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ gcc -framework Foundation hello.m 
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ ls
a.out	hello.m
Alex-Chens-MacBook-Pro:work_area_sandbox achen$ ./a.out 
2010-08-11 23:50:51.017 a.out[2476:903] hello, objective-c!
Alex-Chens-MacBook-Pro:work_area_sandbox achen$
```

 YES! , 成功了，看来的确和通常的C／C＋＋命令行编译运行有区别。

 

通过这个过程，又一次深刻体会了经典”hello，world”例子的重要性，当你成功编译运行了它，语言对你来说就剩下语法和应用了。