单元测试与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 来避免此问题
- 单元测试与main前运行函数__attribute__((constructor))关键字
- __attribute__((constructor)) 修饰的函数在main函数之前执行
- 函数属性__attribute__((constructor))和__attribute__((destructor))
- 函数属性__attribute__((constructor))和__attribute__((destructor))
- gcc __attribute__关键字举例之constructor/destructor
- gcc 函数属性 __attribute__ ((constructor))使用
- __attribute__ ((constructor));
- __attribute__((constructor))
- IOS main函数运行前的dydl动态链接库
- main函数执行前-C/C++运行时库剖析
- __attribute__((constructor)) 和 __attribute__((destructor))
- __attribute__((constructor))和__attribute__((destructor))
- 证明静态函数在main函数运行前就运行了
- GCC __attribute__((constructor)|(destructor))
- __attribute__ ((constructor)) 分享
- Gcc扩展:__attribute__((constructor))
- GCC __attribute__((constructor)|(destructor))
- GCC __attribute__((constructor)|(destructor))
- 关于ociuldr数据导出工具的使用说明
- nvl函数
- ACM的小技巧
- vc try catch捕捉所有异常的问题
- if条件里有两个 或 (||) 符号
- 单元测试与main前运行函数__attribute__((constructor))关键字
- C# Dictionary序列化/反序列化
- ReportViewer 嵌套子报表
- K.Teamwork Brings Profits! 典型的dfs搜索
- 在操作数据库时候出现 sqlite3_open_v2("/data/data/xxx/databases/xxx.db", &handle, 6)failed
- oracle 怎么查看一个数据库中有几个表空间?以及这些表空间的名字?
- 为什么要去火星
- sql server 2000更新技巧&select 查询中带参数,游标中使用exec
- chromium的gdb