在 main() 之前调用 void 函数
Calling void function before main()
我想知道是否可以在不使用临时变量的情况下调用 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);
}
(向原始回答者道歉,我删除了原始帖子,无法给予应有的信任。
相关文章:
- 在c++类上调用void函数
- C++为什么尽管我调用了void函数,它却不起作用
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 使用运算符调用 void 函数时出错<set>
- C++命名空间中调用 void 函数的错误
- 在数组函数指针中调用void
- c++ 检查 Unix 中是否存在目录,如果存在,则调用 void 函数
- 在 main() 之前调用 void 函数
- C 如何在没有错误的情况下调用void函数
- 如何使用数组和参考参数调用void函数
- 如何在C++中调用void foo(int (&)[]) {}?
- 如何从主调用 void 函数
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- 调用void函数
- 如果没有返回,如何向main调用void函数
- 在什么情况下afx_msg可以调用 void OnDestroy( ) 又名 CWnd:OnDestroy()
- 如何在 cout 语句中调用 void 函数
- C++ 错误:使用 argc、*argv[] 和多维数组调用 void 函数时"no matching function to call to "
- c++ 14是否要求delete表达式必须调用' void operator::delete(void*, std::
- 将无符号char*缓冲区强制转换为可接受参数的可调用void指针