【问题标题】:How to compile Objective C++ in GCC?如何在 GCC 中编译 Objective C++?
【发布时间】:2017-07-07 14:30:14
【问题描述】:

我在 Ubuntu 16.04 中安装了 GNUStep 和 gobjc。我可以像这样编译 Objective-C 代码:

gcc codefile.m `gnustep-config --objc-flags` -lobjc -lgnustep-base -o codefile

但我想在 GCC 中编译 Objective-C++ 代码。我该怎么做?

【问题讨论】:

    标签: linux gcc g++ objective-c++


    【解决方案1】:

    您的version of gcc / gobjc 中的Documentation of objc/objc++ dialects in GCC 未列出用于选择方言变体的特定选项。

    只需使用标准文件扩展名“.mm”或“.M”(此外,您可以将 gcc 替换为 g++ 以自动将 C++ 库添加到链接阶段;两种变体都未经测试):

    gcc codefile.mm `gnustep-config --objc-flags` -lobjc -lgnustep-base -o codefile
    g++ codefile.mm `gnustep-config --objc-flags` -lobjc -lgnustep-base -o codefile
    

    ObjC++ 是"simply source code that mixes Objective-C classes and C++ classes"

    Gcc 将根据文件扩展名选择模式,有一个巨大的文件扩展名表和对应的语言模式,Objective-C for .m 和 Objective-C++ for .mm/.M: https://github.com/gcc-mirror/gcc/blob/gcc-4_7_4-release/gcc/gcc.c#L913

    static const struct compiler default_compilers[] =
    {
      /* Add lists of suffixes of known languages here.  If those languages
         were not present when we built the driver, we will hit these copies
         and be given a more meaningful error than "file not used since
         linking is not done".  */
      {".m",  "#Objective-C", 0, 0, 0}, {".mi",  "#Objective-C", 0, 0, 0},
      {".mm", "#Objective-C++", 0, 0, 0}, {".M", "#Objective-C++", 0, 0, 0},
      {".mii", "#Objective-C++", 0, 0, 0},
     . . .
      /* Next come the entries for C.  */
      {".c", "@c", 0, 0, 1},
    

    还有g++ 的-x 选项,允许使用“objective-c++”参数手动选择语言方言(gcc -x objective-c++ ... 或g++ -x objective-c++): https://github.com/gcc-mirror/gcc/blob/1cb6c2eb3b8361d850be8e8270c597270a1a7967/gcc/cp/g%2B%2Bspec.c#L167

    case OPT_x:
     . . . 
          && (strcmp (arg, "c++") == 0
          || strcmp (arg, "c++-cpp-output") == 0
          || strcmp (arg, "objective-c++") == 0
    

    记录在https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html

     -x language
    

    明确指定以下输入文件的语言(而不是让编译器根据文件名后缀选择默认语言)。此选项适用于所有后续输入文件,直到下一个 -x 选项。语言的可能值是:

          c  . . .  c++ . . .
          objective-c  objective-c-header  objective-c-cpp-output
          objective-c++ objective-c++-header objective-c++-cpp-output
    

    【讨论】:

    • 本人使用Objective-C++的经验仅限于macOS,但文件需要以扩展名.mm命名,否则无法使用。我认为这是正确的答案。
    • @osgx 感谢您提供详细信息。我可以像这样用g++ 编译Objective-C++:g++ codefile.mm `gnustep-config --objc-flags` -lobjc -lgnustep-base -o codefile。
    • @H.Al-Amri 在 macOS 上使用 clang,您可以在编译时使用 -ObjC++ 标志。这将覆盖基于文件名的模式检测。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 2012-08-06
    • 2021-05-24
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    相关资源
    最近更新 更多