使用google gtest框架的时候总是有一个疑惑。
每一个用例都是一个testing类的派生,创建完这个类,将这个类的源文件和gtest main一起编译之后,框架就能把这个类里面的方法调用起来?为什么?
这个类是如何被感知到的?
先看个简单例子:
#include "stdio.h"
int hello();
class Hello{
static int x;
};
int Hello::x=hello();
int hello(){
printf("I say hello\n");
return 0;
}
int main(){
printf("I do nothing.\n");
return 0;
}
编译运行这个程序,会发现hello在main的前面执行。
I say hello
I do nothing.
这就牛逼了,一直认为程序总是要从一个固定入口开始的,比如main。然而发现并不是:
#0 hello () at main.cpp:11
#1 0x0000555555554c11 in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at main.cpp:8
#2 0x0000555555554c2d in _GLOBAL__sub_I_g_F () at main.cpp:18
#3 0x000055555555599d in __libc_csu_init ()
#4 0x00007ffff7464b28 in __libc_start_main (main=0x555555554b22 <main()>, argc=1, argv=0x7fffffffe398, init=0x555555555950 <__libc_csu_init>, fini=<optimized out>, rtld_fini=<optimized out>,
stack_end=0x7fffffffe388) at ../csu/libc-start.c:266
#5 0x00005555555549ea in _start ()
关于程序的入口问题,这篇博文讲的很好了:
https://blog.youkuaiyun.com/function_dou/article/details/83268261
利用这个特性可以做一些更有用的事情,比如:
#include "stdio.h"
#include <vector>
using namespace std;
int hello();
typedef int(*PFunc)();
vector<PFunc> g_F;
class Hello{
static int x;
};
int Hello::x=hello();
int hello(){
printf("I say hello\n");
g_F.push_back(hello);
return 0;
}
int main(){
printf("I do nothing.\n");
for(auto f:g_F){
f();
}
return 0;
}
https://www.cnblogs.com/liyuan989/p/4136099.html 这篇博文介绍gtest框架原理介绍的很详细。其中与本文的联系在于:
static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\
GTEST_DISALLOW_COPY_AND_ASSIGN_(\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\
testing类静态成员初始化的时候搞了很多事情。