如何在GCC中编译Objective C++?

问题描述:

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

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

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

Documentation of objc/objc++ dialects in GCC你的version of gcc/gobjc没有列出选择方言变体的特定选项。

只需使用标准的文件扩展名“.mm”或“.M”(你也可以用g++替代gcc自动添加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将基于文件扩展名选择模式,存在一种用于.m和Objective-C++文件扩展名和相应的语言的模式与目标C的巨大表.mm/.Mhttps://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}, 

,还设有 “目标C++” 手动选择语言的方言(gcc -x objective-c++ ...g++ -x objective-c++)的允许参数的g++-x选项: 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选项。语言可能的值有:

+1

我用的Objective-C++经验仅限于Mac系统,但该文件需要扩展名为.mm命名,否则将无法正常工作。我认为这是正确的答案。 –

+1

@osgx感谢您的详细信息。我可以用'g ++'编译Objective-C++,就像这样:''g ++ codefile.mm'gnustep-config --objc-flags' -lobjc -lgnustep-base -o codefile''。 –

+0

@ H.Al-Amri在macOS上使用clang时,编译时可以使用'-ObjC++'标志。这将覆盖基于文件名的模式检测。 – Clearer