上课时候碰到的问题,在main函数之前打印信息怎么做呢?
2、在C里面也是可以实现的,若想在main函数之前运行,可以在想运行的函数的声明(注意这里是声明)之后加上一句“__attribute__((constructor))”来实现;同理,在想运行的函数的声明(要是声明)之后加上一句“__attribute__((destructor))”来实现;
5、当然,在C里面也可以通过结构体实现(类似于类)
方法有以下几种:
1、在C++中通过类的构造函数实现,这样一来,其实也可以实现在main函数之后打印信息:
#include <iostream>
using namespace std;
class a {
public:
a() {
cout << "before the main function" << endl;
}
~a(){
cout << "after the main function" << endl;
};
};
a b;
int main() {
cout << "now main function is working" << endl;
return 0;
}
2、在C里面也是可以实现的,若想在main函数之前运行,可以在想运行的函数的声明(注意这里是声明)之后加上一句“__attribute__((constructor))”来实现;同理,在想运行的函数的声明(要是声明)之后加上一句“__attribute__((destructor))”来实现;
#include <stdio.h>
void before_main()__attribute__((constructor));
void before_main() {
printf("before the main function\n");
}
void after_main()__attribute__((destructor));
void after_main() {
printf("after the main function\n");
}
int main() {
printf("Now main function is working\n");
return 0;
}
3、通过宏定义main函数实现
#include <stdio.h>
void print()
{
#define main main() {printf("Hello World!\n");return 0;}int empty
}
int main()
{
return 0;
}
这个方法比较贼吧。个人感觉实质依然是在main函数里面执行的。
4、其实在main函数之后执行函数还可以用atexit,这里摘抄了他人的代码和解释:
#include<stdio.h>
#include<stdlib.h>
//
// 声明将在 main 函数结束后执行的函数.
// 这样的函数前置声明很特别吧!我以前也没想到过.
//
void fn1(void), fn2(void), fn3(void), fn4(void);
int main(void)
{
//
// 注册需要在 main 函数结束后执行的函数.
// 请注意它们的注册顺序和执行顺序,看看它们的输出结果多有趣!
//
atexit(fn1);
atexit(fn2);
atexit(fn3);
atexit(fn4);
// 这条输出语句具有参照性,它可不是最后一句输出.
puts("This is executed first.");
//
// EXIT_SUCCESS 代表 0,它定义在 stdlib.h 中.
// 我只是顺便提一下,也许你知道,但我担心你不知道,呵呵.
//
return EXIT_SUCCESS;
}
void fn1(void)
{
printf("next.\n");
}
void fn2(void)
{
printf("executed ");
}
void fn3(void)
{
printf("is ");
}
void fn4(void)
{
printf("This ");
}
5、当然,在C里面也可以通过结构体实现(类似于类)
#include <stdio.h>
struct a {
a() {
printf("before the main function\n");
}
~a() {
printf("after the main function\n");
}
};
a b;
int main() {
printf("Now main function is working\n");
return 0;
}
2、在C里面也是可以实现的,若想在main函数之前运行,可以在想运行的函数的声明(注意这里是声明)之后加上一句“__attribute__((constructor))”来实现;同理,在想运行的函数的声明(要是声明)之后加上一句“__attribute__((destructor))”来实现;