如何在 C 中模拟构造函数或静态块
我正在增强一个工具。 请注意,该工具将链接到测试程序,该程序将具有 main( )
函数,因此我的工具不能具有 main.该工具具有测试程序将使用的许多功能。
另外,现在我想为这个工具添加一个计时器。这个想法是:当测试程序链接到该工具并启动时,计时器应该自动启动。
如果这是 C++,我会创建一个带有构造函数的类,这样每当加载该类时,都会首先调用构造函数,并且我可以在构造函数内初始化计时器。
如果这是 Java,我会简单地创建一个全局静态块,并将计时器代码放入静态块内。
但是我的工具在Linux中是纯C语言的,那么我怎样才能实现这个目标呢?
请帮我。
I am enhancing a tool.
Please note that this tool will be linked to test program, which will have main( )
function, so my tool can't have main. What this tool has is a number of functions which the test program will use.
Now additionally, i want to add a timer to this tool. The idea is: when the test program is linked to this tool and starts, the timer should automatically start.
If this was C++, i would have created a class with a constructor, so that whenever the class is loaded, the constructor is called first, and i can initialize my timer inside the constructor.
If this was Java, i would have simply created a global static block, and put the timer code inside the static block.
But my tool is purely in C in Linux, so how can i achieve this goal?
Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这看起来也像你的情况:
如何我如何让 GCC __attribute__ ((constructor)) 在 OSX 下工作?
来自 GCC 文档:
This looks like your case also:
How do I get the GCC __attribute__ ((constructor)) to work under OSX?
From GCC docs:
为调用
main()
的crt*.o
对象文件编写您自己的替代品,并在构建时链接到它。Write your own replacement for the
crt*.o
object file that callsmain()
, and link to it when building.