__attribute__((constructor))
Posted zengkefu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了__attribute__((constructor))相关的知识,希望对你有一定的参考价值。
构造与析构:
#include <stdio.h> #include <stdlib.h> static __attribute__((constructor)) void before() { printf("Hello"); } static __attribute__((destructor)) void after() { printf(" World!\n"); } int main(int args,char ** argv) { printf("main"); return EXIT_SUCCESS; } ~
[[email protected] ~]# ./test.out Hellomain World!
优先级:
[[email protected] ~]# vi test.c #include <stdio.h> #include <stdlib.h> static __attribute__((constructor(101))) void begin101() { printf("Hello-101\n"); } static __attribute__((constructor(102))) void begin102() { printf("Hello-102\n"); } static __attribute__((destructor(150))) void end101() { printf(" World!-101\n"); } static __attribute__((destructor(151))) void end102() { printf(" World!-102\n"); } int main(int args,char ** argv) { return EXIT_SUCCESS; }
[[email protected] ~]# ./test.out Hello-101 Hello-102 World!-102 World!-101
对齐属性:
__attrubte__ ((packed)) 的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐
[[email protected] ~]# vi test.c #include <stdio.h> #include <stdlib.h> #define __u8 unsigned char #define __u16 unsigned short struct str_struct{ __u8 a; __u8 b; __u8 c; __u16 d; } __attribute__ ((packed)); typedef struct { __u8 a; __u8 b; __u8 c; __u16 d; } __attribute__ ((packed)) str; typedef struct { __u8 a; __u8 b; __u8 c; __u16 d; }str_temp __attribute__ ((packed)); typedef struct { __u8 a; __u8 b; __u8 c; __u16 d; }str_nopacked; int main(void) { printf("sizeof str = %d\n", sizeof(str)); printf("sizeof str_struct = %d\n", sizeof(struct str_struct)); printf("sizeof str_temp = %d\n", sizeof(str_temp)); printf("sizeof str_nopacked = %d\n", sizeof(str_nopacked)); return 0; }
[[email protected] ~]# ./test.xx sizeof str = 5 sizeof str_struct = 5 sizeof str_temp = 6 sizeof str_nopacked = 6
以上是关于__attribute__((constructor))的主要内容,如果未能解决你的问题,请参考以下文章
__attribute__ ((__packed__)); 怎么用?
GCC的__attribute__ ((constructor))和__attribute__ ((destructor))