简体   繁体   English

取main()函数的地址是不合法的吗?

[英]Is it illegal to take address of main() function?

According to this answer using function main() is illegal (§3.6.1.3) and a function is used if its name appears in a potentially evaluated expression (§3.2). 根据这个答案, 使用函数main()是非法的 (§3.6.1.3),如果它的名字出现在一个可能被评估的表达式(§3.2)中,则使用一个函数。

Suppose I have this code: 假设我有这个代码:

printf( "%p", &main );

in which name of function main() appears in expression &main . 函数main()名称出现在表达式&main

Will the code above be illegal? 上面的代码是非法的吗?

Yes. 是。 As you quote, the standard says that you cannot use main . 正如你所说,标准说你不能使用main

Note too that the address of a function does not match "%p" . 另请注意,函数的地址与"%p" 匹配。 The corresponding argument must have type void* ; 相应的参数必须具有void*类型; any other type (except maybe char* ) is illegal, and results in undefined behavior. 任何其他类型(除了可能是char* )都是非法的,并导致未定义的行为。

由于main未被“使用”(您不对其进行评估),因此根据您提供的链接,它应该是合法的。

It's not usual to use pointer to main() or the address of main() but.. 这不是通常使用指针main()或地址main()但..

Anyway, it is allowed since, as every function (and any symbol, eg variable) it has its own address. 无论如何,它被允许,因为每个函数(和任何符号,例如变量)它都有自己的地址。 And the address of main() may be needed - especially when you write code for embedded systems and you play with dynamic loading of the code or run-time inspection. 并且可能需要main()的地址 - 尤其是当您为嵌入式系统编写代码并且使用动态加载代码或运行时检查时。 Or there are a bootloader and actual running firmware. 或者有一个引导加载程序和实际运行的固件。

Often main() is an entry point to the dynamically loaded code (eg from FLASH to RAM) and thus it is referenced (called directly or assigned to the relevant pointer) in bootloader. 通常main()是动态加载代码的入口点(例如,从FLASH到RAM),因此它在引导加载程序中被引用(直接调用或分配给相关指针)。

Refer to MicroC-OS/II or VxWorks - both use main() in this way 参考MicroC-OS / II或VxWorks - 都以这种方式使用main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM