我在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++代碼。我該怎麼做?
我在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
/.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},
,還設有 「目標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選項。語言可能的值有:
我用的Objective-C++經驗僅限於Mac系統,但該文件需要擴展名爲.mm命名,否則將無法正常工作。我認爲這是正確的答案。 –
@osgx感謝您的詳細信息。我可以用'g ++'編譯Objective-C++,就像這樣:''g ++ codefile.mm'gnustep-config --objc-flags' -lobjc -lgnustep-base -o codefile''。 –
@ H.Al-Amri在macOS上使用clang時,編譯時可以使用'-ObjC++'標誌。這將覆蓋基於文件名的模式檢測。 – Clearer