OC代码转C++代码的生成

使用clang编译器将Objective-C代码编译成C语言代码, 并生成在一个.cpp的 C++文件中。具体的命令行是:

$ cd 当前文件夹 
$ clang -rewrite-objc ViewController.m

可能会遇到一个错误就是如下:

解决办法是将之前执行的命令替换成为:

$ clang -x objective-c -rewrite-objc -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk ViewController.m

这时, 你会发现, 你的文件夹中多了一个.cpp的文件, 证明解决了这个问题。

一、如果你觉得这个命令很繁琐不易记, 你可以采用 alias来起一个别名来代替这个命令。

  • 1.打开终端, 键入命令 vim ~/.bash_profile

  • 2.在vim界面输入i进入编辑编辑状态并且键入:jkrewriteoc是我自己起的

    alias jkrewriteoc='clang -x objective-c -rewrite-objc -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk'
    
  • 3.键入完毕后,点击Esc退出编辑,再按 Shift+: ,最后再按:wq保存并退出vim文件并保存

  • 4.键入命令source ~/.bash_profile(必须要执行这句)

  • 二、优化后的使用

    $ cd 当前文件夹 
    $ jkrewriteoc ViewController.m
    

    解释:优化后:也就是起别名,

    jkrewriteoc ViewController.m      
    

    上下两句等同

    $ clang -x objective-c -rewrite-objc -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk ViewController.m
    

    在使用clang转换OC为C++代码时,可能会遇到以下问题

    cannot create __weak reference in file using manual reference

  • 解决方案:支持ARC、指定运行时系统版本,比如,在-rewrite-objc 后面添加 -fobjc-arc -fobjc-runtime=ios-8.0.0

  • 出现问题前如下:

    $ clang -x objective-c -rewrite-objc -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk ViewController.m