使用 g++ 编译 Objective-C 项目时出现运行时错误

Runtime error when compiling Objective-C project using g++

我使用 Objective-C 做了一个非常小的项目,如果我 运行 使用 Xcode,它工作得很好。

但是,我需要使用以下命令行编译它:

g++ Main.mm -o Main `gnustep-config --objc-flags` `gnustep-config --base-libs` -O2 -DONLINE_JUDGE -DBOJ

此命令行是我要上传我的代码进行编译的站点用于编译 Objective-C 个项目的命令。

但是,每当我使用该命令行进行编译时,我都会收到 运行使用 NSMutableArrayNSSetNSString.

的时间错误

错误:

zsh: command not found: gnustep-config
zsh: command not found: gnustep-config
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_NSMutableArray", referenced from:
      objc-class-ref in Main-49f6e3.o
  "_OBJC_CLASS_$_NSSet", referenced from:
      objc-class-ref in Main-49f6e3.o
  "_OBJC_CLASS_$_NSString", referenced from:
      objc-class-ref in Main-49f6e3.o
  "___CFConstantStringClassReference", referenced from:
      CFString in Main-49f6e3.o
  "_objc_msgSend", referenced from:
      _main in Main-49f6e3.o
  "_objc_opt_new", referenced from:
      _main in Main-49f6e3.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

而且,这是我的源代码:

#import <Foundation/Foundation.h>

int main(void) {
    int num = 0;
    int answer = 0;
    scanf("%i", &num);
    NSMutableArray *cl = [NSMutableArray new];
    
    for (int k = 0; k < num; k++) {
        char str[4];
        getchar();
        scanf("%[^\n]s", str);
        NSString *userInput = [NSString stringWithUTF8String:str];
        
        if (userInput.length == 1) {
            [cl removeObjectAtIndex:0];
        } else {
            [cl addObject:[userInput substringFromIndex:[userInput length] - 1]];
        }
        
        NSMutableArray *result = [NSMutableArray new];
        for (int i = 1; i <= cl.count; i++) {
            for (int j = 0; j <= cl.count-i; j++) {
                [result addObject:[[cl subarrayWithRange:NSMakeRange(j, i)] componentsJoinedByString:@""]];
            }
        }
        
        answer += [[NSSet setWithArray:result] allObjects].count;
    }
    
    printf("%d\n", answer%1000000007);
    
    return 0;
}

这些是 linker 错误,不是运行时错误。

您需要 link 针对 objc 库和 Foundation 框架。尝试:

g++ Main.mm -lobjc -framework Foundation ...