gpt4 book ai didi

c - 如何在 C 中模拟构造函数或静态 block

转载 作者:可可西里 更新时间:2023-11-01 11:47:45 25 4
gpt4 key购买 nike

我正在改进一个工具。请注意,此工具将链接到测试程序,该程序将具有 main( ) 函数,因此我的工具不能有 main。该工具具有的是测试程序将使用的许多功能。

另外,我想给这个工具添加一个计时器。这个想法是:当测试程序链接到这个工具并启动时,计时器应该自动启动。

如果这是 C++,我会创建一个带有构造函数的类,这样每当加载该类时,都会先调用构造函数,然后我可以在构造函数中初始化我的计时器。

如果这是 Java,我会简单地创建一个全局静态 block ,并将计时器代码放在静态 block 中。

但是我的工具在 Linux 中是纯 C 的,那么我该如何实现这个目标呢?

请帮帮我。

最佳答案

这看起来也像你的情况:

How do I get the GCC __attribute__ ((constructor)) to work under OSX?

来自 GCC 文档:

constructor
destructor
constructor (priority)
destructor (priority)

The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.

关于c - 如何在 C 中模拟构造函数或静态 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6276692/

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