llvm / llvm/llvm-project

Objective-C constant literals only work for Objective-C++, but not Objective-C

Open
#180,673 9 comments 0 reactions 0 assignees View on GitHub
clang:frontend objective-c
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

Xcode has supported `-fobjc-constant-literals` since Xcode 13. Even though open source clang doesn't accept the flag, it seems to support the underlying feature by default. But surprisingly that only works for Objective-C++ but not Objective-Cc. See below for reproducer and more details.

`$ cat lit.m`

```objective-c
#import

static NSDictionary * const myConstantDictionary = @{ @"something_awesome" : @YES };
static NSArray * const myArray = @[ @1, @2, @3, @4 ];
static NSNumber * const answerToLife = @42;

int main(int argc, char *argv[]) {
@autoreleasepool {
NSLog(@"%@", myConstantDictionary);
NSLog(@"%@", myArray);
NSLog(@"%@", answerToLife);
}
return 0;
}
```
```
# With Xcode clang, both of the following commands succeed:
$ clang -target arm64-apple-macosx15.5 -fsyntax-only -x objective-c lit.m
$ clang -target arm64-apple-macosx15.5 -fsyntax-only -x objective-c++ lit.m

# With open source clang, building for Objective-C++ succeeds:
$ clang -isysroot -target arm64-apple-macosx15.5 -fsyntax-only -x objective-c++ lit.m
# But building for Objective-C fails:
$ clang -isysroot -target arm64-apple-macosx15.5 -fsyntax-only -x objective-c lit.m
lit.m:3:52: error: initializer element is not a compile-time constant
3 | static NSDictionary * const myConstantDictionary = @{ @"something_awesome" : @YES };
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lit.m:4:34: error: initializer element is not a compile-time constant
4 | static NSArray * const myArray = @[ @1, @2, @3, @4 ];
| ^~~~~~~~~~~~~~~~~~~
lit.m:5:40: error: initializer element is not a compile-time constant
5 | static NSNumber * const answerToLife = @42;
| ^~~
3 errors generated.

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.