你可以在c中运行一个初始化函数吗? [英] Can you run a function on initialization in c?

查看:18
本文介绍了你可以在c中运行一个初始化函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在程序加载时是否有运行函数的机制或​​技巧?

Is there an mechanism or trick to run a function when a program loads?

我正在努力实现的目标......

What I'm trying to achieve...

void foo(void)
{
}

register_function(foo);

但显然 register_function 不会运行.

but obviously register_function won't run.

所以 C++ 中的一个技巧是使用初始化来使函数运行

so a trick in C++ is to use initialization to make a function run

类似

int throwaway = register_function(foo);

但这在 C 中不起作用.所以我正在寻找一种使用标准 C 的方法(没有特定于平台/编译器的)

but that doesn't work in C. So I'm looking for a way around this using standard C (nothing platform / compiler specific )

推荐答案

如果你使用的是 GCC,你可以通过 constructor 函数属性来做到这一点,例如:

If you are using GCC, you can do this with a constructor function attribute, eg:

#include <stdio.h>

void foo() __attribute__((constructor));

void foo() {
    printf("Hello, world!
");
}

int main() { return 0; }

但是,在 C 中没有可移植的方式来执行此操作.

There is no portable way to do this in C, however.

不过,如果您不介意弄乱您的构建系统,那么您还有更多选择.例如,您可以:

If you don't mind messing with your build system, though, you have more options. For example, you can:

#define CONSTRUCTOR_METHOD(methodname) /* null definition */

CONSTRUCTOR_METHOD(foo)

现在编写一个构建脚本来搜索 CONSTRUCTOR_METHOD 的实例,并将对它们的一系列调用粘贴到生成的 .c 文件中的函数中.在 main() 的开头调用生成的函数.

Now write a build script to search for instances of CONSTRUCTOR_METHOD, and paste a sequence of calls to them into a function in a generated .c file. Invoke the generated function at the start of main().

这篇关于你可以在c中运行一个初始化函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆