【问题标题】:Main function Concept in C [closed]C中的主要功能概念
【发布时间】:2016-08-25 12:57:49
【问题描述】:

我想知道是否可以编写两个函数,其中一个函数在 main 函数之前执行,另一个函数在 main 函数之后执行?这是在一次问答比赛中提出的,我发现很难找到答案。

【问题讨论】:

标签: c


【解决方案1】:

对于在退出时运行的东西,您可以使用atexit

#include <stdio.h>
#include <stdlib.h>


void we_are_dying()
{
       printf("Get the doctor!\n");

}

int main(void) {
    atexit(we_are_dying);
    // your code goes here
    printf("We are done\n");
    return 0;
}

对于在 main 之前运行的东西,我认为这是不可能的。

【讨论】:

  • 好吧,您可以在调用 main() 之前破解 crt 以调用 'preMain()',但这似乎与 OP 的问题一样毫无意义。
【解决方案2】:

GCC(GNU Compiler Collection)编译器为 C 添加了许多通常被忽视的扩展。 这些添加的扩展可以帮助我们简化 C 应用程序的开发。扩展之一是添加属性。根据指定的属性,我们可以指示编译器对函数或变量进行特殊处理。

使用constructor属性,我们可以指定main()函数执行前后要执行的函数。请参考下面给出的示例(取自 - https://www.hackerearth.com/notes/c-program-callling-a-function-before-main/)。

#include<stdio.h>

/* Apply the constructor attribute to startFunc() so that it
    is executed before main() */
void startFunc (void) __attribute__ ((constructor));

/* Apply the destructor attribute to lastFunc() so that it
   is executed after main() */
void lastFunc (void) __attribute__ ((destructor));

void startFunc (void)
{
    printf ("startup code before main()\n");
}

void lastFunc (void)
{
    printf ("Function after main()\n");
}

int main (void)
{
    printf ("In Main Function\n");
    return 0;
}

我上面提到的链接显示了另一种实现启动和退出功能的方法。但是 gcc 不支持 #pragma startup .. #pragma exit ...。 在 gcc 和 clang 中,您应该改用 __attribute__((constructor)) 和 __attribute__((destructor))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多