gpt4 book ai didi

Objective-C : "Hello world"已编译!没有基础标题。为什么?

转载 作者:太空宇宙 更新时间:2023-11-04 00:21:02 25 4
gpt4 key购买 nike

考虑以下代码:

//#import <Foundation/Foundation.h>

int main(int argc, const char *argv[]) {
@autoreleasepool {
NSLog(@"Hello World!");
}
return 0;
}

我不明白为什么它可以构建和运行?没有 Foundation 标题!

对我来说,C 编译器编译此代码时不带 header (即不带声明)仍然很奇怪。奇怪的是,编译器以某种方式将我的函数与已编译的代码 (Foundation) 匹配并成功。是否有一些指向 C 标准的链接可以解释编译器如何解析识别为函数且之前从未声明过的 token ?

请解释!!

更新:这些如果不是由于预编译的头文件

谢谢!但不是。我通过以下方式对其进行了测试 - 只需在 vi 编辑器中键入 Hello World 代码并将其保存为 main.m 文件。比从终端用 clang 编译它。 e-thing 一切正常,只有 1 个警告:

main.m:8:9: warning: implicitly declaring library function 'NSLog' with type 'void (id, ...)' NSLog(@"Hello World!");
^ main.m:8:9: note: please include the header <Foundation/NSObjCRuntime.h> or explicitly provide a declaration for 'NSLog'
1 warning generated.

更新:只需一步一步附上所有图片: The only file in directory main.m Contents of main.m - VIM Compiling ... Compiled! Test run of the application built

最佳答案

没有理由不编译。如您所见,如果没有该 header ,编译器会假设 NSLog 是一个具有签名 void NSLog(id, ...) 的函数。在这种情况下,您甚至更幸运,因为该签名恰好与真正的函数声明兼容 - 这意味着您的程序实际上什至也能正常工作:

FOUNDATION_EXPORT void NSLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2);

请注意,如果不链接到 Foundation,构建将不会成功:

$ make example
cc example.m -o example
example.m:3:9: warning: implicitly declaring library function 'NSLog' with type
'void (id, ...)'
NSLog(@"Hello World!");
^
example.m:3:9: note: please include the header <Foundation/NSObjCRuntime.h> or
explicitly provide a declaration for 'NSLog'
1 warning generated.
Undefined symbols for architecture x86_64:
"_NSLog", referenced from:
_main in example-943cd4.o
"___CFConstantStringClassReference", referenced from:
CFString in example-943cd4.o
"_objc_autoreleasePoolPop", referenced from:
_main in example-943cd4.o
"_objc_autoreleasePoolPush", referenced from:
_main in example-943cd4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [example] Error 1

需要添加-framework Foundation:

$ CFLAGS="-framework Foundation" make example
cc -framework Foundation example.m -o example
example.m:3:9: warning: implicitly declaring library function 'NSLog' with type
'void (id, ...)'
NSLog(@"Hello World!");
^
example.m:3:9: note: please include the header <Foundation/NSObjCRuntime.h> or
explicitly provide a declaration for 'NSLog'
1 warning generated.

关于 Objective-C : "Hello world"已编译!没有基础标题。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24209079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com