在 main() 之前调用 void 函数

Calling void function before main()

本文关键字:调用 void 函数 main      更新时间:2023-10-16

我想知道是否可以在不使用临时变量的情况下调用 void 函数。 例如,在下面的代码块中...

#include <iostream>
void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}
int g_foo = (earlyInit(), 0);
int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}

。我不需要g_foo,宁愿它不存在。有没有办法在没有中间温度变量的情况下调用 void 函数?

我想知道是否可以在不使用临时变量的情况下调用 void 函数。 例如,在下面的代码块中。

该语言没有提供任何此类机制。正如其他答案所指出的那样,可能有特定于编译器的方法可以做到这一点。

但是,我认为您的方法没有任何问题。我经常使用以下模式。

#include <iostream>
namespace mainNS  // A file-specific namespace.
{
   void earlyInit()
   {
      std::cout << "The void before the world." << std::endl;
   }
   struct Initializer
   {
      Initializer();
   };
}
using namespace mainNS;
static Initializer initializer;
Initializer::Initializer()
{
   earlyInit();
   // Call any other functions that makes sense for your application.
}
int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}

检查编译器是否支持 #pragma startup(或等效(,例如:

#include <iostream>
void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}
#pragma startup earlyInit
int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}
这个

问题的答案引起了__attribute__((constructor))的注意,但是,由于我不完全理解的原因,如果在void函数使用时SIGSEGV std::cout(printf没有导致SIGSEGV(。

我之前发布了这个问题的一个版本(但愚蠢地删除了它(。当时的一位回答者向我指出了这篇优秀的文章,其中讨论了情况和解决方案:

http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html

解决方案的摘录(略微修改以通过编译(在这里:

#include <cstdio>
#include <cstdlib>
void preinit(int argc, char * * argv, char * * envp) {
  printf("%sn", __FUNCTION__);
}
void init(int argc, char * * argv, char * * envp) {
  printf("%sn", __FUNCTION__);
}
void fini() {
  printf("%sn", __FUNCTION__);
}
__attribute__((section(".init_array"))) typeof (init) * __init = init;
__attribute__((section(".preinit_array"))) typeof (preinit) * __preinit = preinit;
__attribute__((section(".fini_array"))) typeof (fini) * __fini = fini;
void __attribute__((constructor)) constructor() {
  printf("%sn", __FUNCTION__);
}
void __attribute__((destructor)) destructor() {
  printf("%sn", __FUNCTION__);
}
void my_atexit() {
  printf("%sn", __FUNCTION__);
}
void my_atexit2() {
  printf("%sn", __FUNCTION__);
}
int main() {
  atexit(my_atexit);
  atexit(my_atexit2);
}

(向原始回答者道歉,我删除了原始帖子,无法给予应有的信任。