Skip to content

Instantly share code, notes, and snippets.

@MRobertEvers
Last active November 26, 2021 15:18
Show Gist options
  • Save MRobertEvers/935a9a33295db867b55bb882434bacc8 to your computer and use it in GitHub Desktop.
Save MRobertEvers/935a9a33295db867b55bb882434bacc8 to your computer and use it in GitHub Desktop.
Compile Objective-Cpp Code (Mac)
```
# -lstdc++ links against the cpp std lib
# -framework Foundation includes the Objective c(pp) foundation
# -fobjc-arc Enables ARC
clang -lstdc++ -framework Foundation -fobjc-arc main.mm -o hello
./hello
```
```objective-c
// main.mm
#import <iostream>
#import <Foundation/Foundation.h>
class Bob {
public:
Bob() {
NSLog(@"Bob");
std::cout << "Bob" << std::endl;
}
~Bob() {
NSLog(@"~Bob");
std::cout << "~Bob" << std::endl;
}
};
class Alice {
public:
Alice() {
NSLog(@"Alice");
std::cout << "Alice" << std::endl;
}
~Alice() {
NSLog(@"~Alice");
std::cout << "~Alice" << std::endl;
}
};
@interface BobbyC: NSObject {
Bob *ptr;
Alice Alice;
}
- (id)init;
// - (void)dealloc;
@end
@implementation BobbyC
- (id) init {
NSLog(@"init BobbyC");
self = [super init];
ptr = new Bob();
return self;
}
- (void) dealloc {
NSLog(@"dealloc BobbyC");
delete ptr;
}
@end
class Wallace {
public:
Wallace() {
std::cout << "Wallace" << std::endl;
this->bobby = [[BobbyC alloc] init];
}
~Wallace() {
std::cout << "~Wallace" << std::endl;
}
private:
BobbyC* bobby;
};
int main() {
// Auto release behavior
@ autoreleasepool {
BobbyC* bobby = [[BobbyC alloc] init];
// bobby is 'released' here.
}
// Default destructor behavior works.
{
Bob b;
Wallace w;
// Wallace destructor calls release on it's BobbyC member
}
return 0;
}
```
This program produces the following output.
```
2021-11-25 18:38:09.028 hello[76243:1828134] Alice
Alice
2021-11-25 18:38:09.029 hello[76243:1828134] init BobbyC
2021-11-25 18:38:09.029 hello[76243:1828134] Bob
Bob
2021-11-25 18:38:09.029 hello[76243:1828134] dealloc BobbyC
2021-11-25 18:38:09.029 hello[76243:1828134] ~Bob
~Bob
2021-11-25 18:38:09.029 hello[76243:1828134] ~Alice
~Alice
2021-11-25 18:38:09.029 hello[76243:1828134] Bob
Bob
Wallace
2021-11-25 18:38:09.029 hello[76243:1828134] Alice
Alice
2021-11-25 18:38:09.029 hello[76243:1828134] init BobbyC
2021-11-25 18:38:09.029 hello[76243:1828134] Bob
Bob
~Wallace
2021-11-25 18:38:09.029 hello[76243:1828134] dealloc BobbyC
2021-11-25 18:38:09.029 hello[76243:1828134] ~Bob
~Bob
2021-11-25 18:38:09.029 hello[76243:1828134] ~Alice
~Alice
2021-11-
```
ARC Stuff
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html#//apple_ref/doc/uid/10000011i
Bob can also be a non-pointer member in BobbyC
```objective-c
@interface BobbyC: NSObject {
Bob bob;
}
```
What is frameworks?
https://stackoverflow.com/questions/15311263/does-gcc-clangs-framework-option-work-on-linux
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment