之前的主执行任何功能 [英] Execute any function before main

查看:140
本文介绍了之前的主执行任何功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想之前的主执行用户定义函数()。
是否有可能在来执行函数main()在C?

 总和(INT A,INT B){回报(A + B); }G_SUM =总和(1,5);主要(){
  总和(5,6);
  的printf(%D,G_SUM);
}


解决方案

  

是否有可能之前执行一个函数main()


是的,它是可能的,如果你正在使用gcc和g ++编译那么它可以用做 __ __属性((构造函数))

示例:

 的#include<&stdio.h中GT;无效beforeMain(无效)__attribute __((构造函数));无效beforeMain(无效)
{
  的printf(\\ n这是之前的主\\ n);
}诠释的main()
{
 的printf(\\ n这是我的主要\\ n);
 返回0;
}

I want to execute user define function before main(). Is it possible to execute a function before main() in c?

sum(int a, int b) {   return (a+b); }

g_sum = sum(1, 5);

main(){
  sum(5, 6);
  printf("%d", g_sum);
}

解决方案

Is it possible to execute a function before main()

Yes it is possible if you are using gcc and g++ compilers then it can be done by using __attribute__((constructor))

Example:

#include <stdio.h>

void beforeMain (void) __attribute__((constructor));

void beforeMain (void)
{
  printf ("\nThis is before main\n");
}

int main ()
{
 printf ("\nThis is my main \n");
 return 0;
}

这篇关于之前的主执行任何功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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