Call a function before main [duplicate]

人盡茶涼 提交于 2019-11-26 09:28:07

问题


Possible Duplicate:
Is main() really start of a C++ program?

Is possible to call my function before program\'s startup? How can i do this work in C++ or C?


回答1:


You can have a global variable or a static class member.

1) static class member

//BeforeMain.h
class BeforeMain
{
    static bool foo;
};

//BeforeMain.cpp
#include "BeforeMain.h"
bool BeforeMain::foo = foo();

2) global variable

bool b = foo();
int main()
{
}

Note this link - Mirror of http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14 / proposed alternative - posted by Lundin.




回答2:


In C++ there is a simple method: use the constructor of a global object.

class StartUp
{
public:
   StartUp()
   { foo(); }
};

StartUp startup; // A global instance

int main()
{
    ...
}

This because the global object is constructed before main() starts. As Lundin pointed out, pay attention to the static initialization order fiasco.




回答3:


If using gcc and g++ compilers then this can be done by using __attribute__((constructor))

eg::
In gcc (c) ::

#include <stdio.h>

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

void beforeMain (void)
{
  printf ("\nbefore main\n");
}

int main ()
{
 printf ("\ninside main \n");
 return 0;
}

In g++ (c++) ::

#include <iostream>
using namespace std;
void beforeMain (void) __attribute__((constructor));

void beforeMain (void)
{
  cout<<"\nbefore main\n";
}

int main ()
{
  cout<<"\ninside main \n";
  return 0;
}



回答4:


In C++ it is possible, e.g.

static int dummy = (some_function(), 0);

int main() {}

In C this is not allowed because initializers for objects with static storage duration must be constant expressions.




回答5:


I would suggest you to refer this link..

http://bhushanverma.blogspot.in/2010/09/how-to-call-function-before-main-and.html

For GCC compiler on Linux/Solaris:

#include

void my_ctor (void) __attribute__ ((constructor));
void my_dtor (void) __attribute__ ((destructor));

void
my_ctor (void)
{
printf ("hello before main()\n");
}

void
my_dtor (void)
{
printf ("bye after main()\n");
}

int
main (void)
{
printf ("hello\n");
return 0;
}

$gcc main.c
$./a.out
hello before main()
hello
bye after main()


来源:https://stackoverflow.com/questions/10897552/call-a-function-before-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!