单元测试与main前运行函数__attribute__((constructor))关键字

来源:互联网 发布:软件使用授权书模板 编辑:程序博客网 时间:2024/06/05 12:01

为了便于单元测试,做了一个utl_cmd的小模块,它会负责插入命令,解析命令并执行。

利用这些命令,可以方便的在程序运行过程中对模块进行测试。

而这里有个比较麻烦的问题是,必须要调用utl_cmd_insert先把测试命令插入到命令序列中。

否则utl_cmd模块,也不知道都有哪些命令可以支持。

 

为解决此问题,忽然想起来之前看DirectFB代码时,遇到过main函数运行前自动运行的函数。

经多方查找,终于实现了。

 

#include <stdio.h>#include <stdlib.h> static void foo(void) __attribute__ ((constructor));static void bar(void) __attribute__ ((destructor));  int main(int argc, char *argv[]){        printf("foo == %p\n", foo);        printf("bar == %p\n", bar);         exit(EXIT_SUCCESS);} void foo(void){        printf("hi dear njlily!\n");} void bar(void){        printf("missing u! goodbye!\n");}lfx@ubuntu:temp$ gcc main.c lfx@ubuntu:temp$ ./a.out hi dear njlily!foo == 0x8048473bar == 0x8048487missing u! goodbye!

 

利用这个特性,就不需要再在main函数中先调用插入命令的函数了。

 

int mplayer_test_init() __attribute__((constructor)) ;int mplayer_test_init(){char *helper = "\tmplayer prepare [WINDOW COUNT]\n""\tmplayer play [chn] [fname]\n""\tmplayer stop [chn]\n""\tmplayer over\n""\tmplayer step [chn]\n""\tmplayer back [chn]\n""\tmplayer fast [chn] [speed 2,4,8,16,32]\n""\tmplayer slow [chn] [speed 2,4,8,16,32]\n""\tmplayer pause [chn]\n""\tmplayer resume [chn]\n""\tmplayer allplay\n""\tmplayer allspeed [fast | slow] [speed]\n""\tmplayer allstop\n";utl_cmd_insert("mplayer", "mplayer test", helper, mplayer_main);return 0;}


 还有个需要注意之处:

如果,测试代码在一个单独的模块,单独的文件中,而这个文件中的任何函数都没被外部调用的话,

可能会导致自动运行不成功。

原因是,链接过程中,将这个文件整个的删除掉了。

为了避免此问题的发生,可以在链接时,加入-Wl,--whole-archive  -l(你的库)   -Wl,--no-whole-archive 来避免此问题

 

 

 

原创粉丝点击