__attribute__中constructor和destructor

原文地址:https://www.cnblogs.com/alantu2018/p/8465919.html

1、前言

  最近看到一份代码,看到一个函数前面用__attribute__((destructor))修饰,当时感觉有点怪怪的,搜了整个程序,也没发现哪个地方调用这个函数。于是从字面意思猜想,该函数会在程序结束后自动调用,与C++中的析构函数类似。第一次接触GNU下的attribute,总结一下。

2、__attribute__介绍

  __attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。__attribute__前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数

  __attribute__语法格式为:__attribute__ ( ( attribute-list ) )

  若函数被设定为constructor属性,则该函数会在main()函数执行之前被自动的执行。类似的,若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。例如下面的程序:

复制代码
复制代码
#include <stdio.h>
#include <stdlib.h>
static int * g_count = NULL;
__attribute__((constructor)) void load_file()
{
    printf("Constructor is called.
");
    g_count = (int *)malloc(sizeof(int));
    if (g_count == NULL)
    {
    fprintf(stderr, "Failed to malloc memory.
");
    }
}
__attribute__((destructor)) void unload_file()
{
    printf("destructor is called.
");
    if (g_count)
    free(g_count);
}
int main()
{
    return 0;
}
复制代码
复制代码

程序执行结果如下:

3、参考网址

  关于__attribute__的更多更加详细的介绍可以参考:

http://blog.csdn.net/polisan/article/details/5031142

http://blog.csdn.net/ithomer/article/details/6566739

GCC __attribute__((constructor)|(destructor))

在阅读TGTD的代码时发现了一个非常诡异的问题,声明了一个空的全局数组,在使用的时候却发现数组非空,在main()入口时数组已经非空.数组时在什么地方被赋值了呢?最后发现__attribute__这个东东在起作用,类似于全局变量类的构造函数在main()前被调用.

__attribute__((constructor)) 
__attribute__((destructor))

  1. /* test.c */  
  2.   
  3. #include<stdio.h>  
  4. __attribute__((constructor)) void before_main()  
  5. {  
  6.    printf("before main/n");  
  7. }  
  8.   
  9. __attribute__((destructor)) void after_main()  
  10. {  
  11.    printf("after main/n");  
  12. }  
  13.   
  14. int main()  
  15. {  
  16.    printf("in main/n");  
  17.    return 0;  
  18. }  

$ gcc test.c -o test 
$ ./test 
before main 
in main 
after main

根据上面的代码以及输出结果,我们可以猜到__attribute__((constructor))表示这段代码将在main函数前调用,就像在C++里面的全局变量类的构造一样.

说到C++里面的全局类对象的构造,我们不禁要问全局类对象的构造跟__attribute__((constructor))以及destructor谁在前谁在后呢?

/*test2.cpp*/

  1. #include<iostream>  
  2. using namespace std;  
  3. __attribute__((constructor)) void before_main()  
  4. {  
  5.     cout<<"Before Main"<<endl;  
  6. }  
  7. __attribute__((destructor)) void after_main()  
  8. {  
  9.     cout<<"After Main"<<endl;  
  10. }  
  11. class AAA{  
  12.     public:  
  13.     AAA(){  
  14.         cout<<"AAA construct"<<endl;  
  15.     }     
  16.     ~AAA(){  
  17.         cout<<"AAA destructor" <<endl;  
  18.     }     
  19. };  
  20. AAA A;  
  21. int main()  
  22. {  
  23.     cout<<"in main"<<endl;  
  24.     return 0;  
  25. }  

$ make test2

$ ./test2

AAA construct 
Before Main 
in main 
AAA destructor 
After Main

可以看到全局类的构造过程发生在before_main()函数前面,而析构也发生在after_main()前面.

__attribute__机制介绍

1. __attribute__

GNU C的一大特色(却不被初学者所知)就是__attribute__机制。

__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)

__attribute__前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数

__attribute__语法格式为:

__attribute__ ( ( attribute-list ) )

函数属性(Function Attribute),函数属性可以帮助开发者把一些特性添加到函数声明中,从而可以使编译器在错误检查方面的功能更强大。

__attribute__机制也很容易同非GNU应用程序做到兼容。

GNU CC需要使用 –Wall,这是控制警告信息的一个很好的方式。下面介绍几个常见的属性参数。

 

2. format

该属性可以使编译器检查函数声明和函数实际调用参数之间的格式化字符串是否匹配。它可以给被声明的函数加上类似printf或者scanf的特征,该功能十分有用,尤其是处理一些很难发现的bug。

format的语法格式为:

format ( archetype,  string-index,  first-to-check )

format属性告诉编译器,按照printf,scanf,strftime或strfmon的参数表格式规则对该函数的参数进行检查。archetype:指定是哪种风格;

string-index:指定传入函数的第几个参数是格式化字符串;

first-to-check:指定从函数的第几个参数开始按上述规则进行检查。

具体使用格式如下:

__attribute__( ( format( printf,m,n ) ) )

__attribute__( ( format( scanf,m,n ) ) )

其中参数m与n的含义为:

m:第几个参数为格式化字符串(format string);

n:参数集合中的第一个,即参数“…”里的第一个参数在函数参数总数排在第几

注意,有时函数参数里还有“隐身”的呢,后面会提到;

在使用上,__attribute__((format(printf,m,n)))是常用的,而另一种却很少见到。

下面举例说明,其中myprint为自己定义的一个带有可变参数的函数,其功能类似于printf:

//m=1;n=2

extern void  myprint( const char *format,… ) __attribute__( ( format( printf,1,2 ) ) );

//m=2;n=3

extern void  myprint( int l,const char *format,... ) __attribute__( ( format( printf,2,3 ) ) );

需要特别注意的是,如果myprint是一个函数的成员函数,那么m和n的值可有点“悬乎”了,例如:

//m=3;n=4

extern void  myprint( int l,const char *format,... ) __attribute__( ( format( printf,3,4 ) ) );

其原因是,类成员函数的第一个参数实际上一个“隐身”的“this”指针。(有点C++基础的都知道点this指针,不知道你在这里还知道吗?)
这里给出测试用例:attribute.c,代码如下:

extern void myprint(const char *format,...) __attribute__((format(printf,1,2)));

void test()

{

         myprint("i=%d/n",6);

         myprint("i=%s/n",6);

         myprint("i=%s/n","abc");

        myprint("%s,%d,%d/n",1,2);

}

运行$gcc –Wall –c attribute.c attribute后,输出结果为:

attribute.c: In function `test':

attribute.c:7: warning: format argument is not a pointer (arg 2)

attribute.c:9: warning: format argument is not a pointer (arg 2)

attribute.c:9: warning: too few arguments for format

如果在attribute.c中的函数声明去掉__attribute__((format(printf,1,2))),再重新编译,

既运行$gcc –Wall –c attribute.c attribute后,则并不会输出任何警告信息。

注意,默认情况下,编译器是能识别类似printf的“标准”库函数。

 

3. noreturn

该属性通知编译器函数从不返回值。

当遇到函数需要返回值却还没运行到返回值处就已退出来的情况,该属性可以避免出现错误信息。C库函数中的abort()和exit()的声明格式就采用了这种格式

extern void  exit(int)   __attribute__( ( noreturn ) );

extern void  abort(void)  __attribute__( ( noreturn ) );

为了方便理解,大家可以参考如下的例子:

//name: noreturn.c     ;测试__attribute__((noreturn))

extern void  myexit();

int  test( int  n )

{

    if ( n > 0 )

    {

            myexit();

            /* 程序不可能到达这里 */

    }

    else

    {

           return 0;

    }

}

编译$gcc –Wall –c noreturn.c  显示的输出信息为:

noreturn.c: In function `test':

noreturn.c:12: warning: control reaches end of non-void function

警告信息也很好理解,因为你定义了一个有返回值的函数test却有可能没有返回值,程序当然不知道怎么办了!加上__attribute__((noreturn))则可以很好的处理类似这种问题。把extern void myexit();修改为:

extern void  myexit() __attribute__((noreturn));

之后,编译不会再出现警告信息。

 

4. const

该属性只能用于带有数值类型参数的函数上,当重复调用带有数值参数的函数时,由于返回值是相同的。所以此时编译器可以进行优化处理,除第一次需要运算外, 其它只需要返回第一次的结果。

该属性主要适用于没有静态状态(static state)和副作用的一些函数,并且返回值仅仅依赖输入的参数。为了说明问题,下面举个非常“糟糕”的例子,该例子将重复调用一个带有相同参数值的函数,具体如下:

extern int  square( int  n ) __attribute__ ( (const) );

for (i = 0; i < 100; i++ )                 

{      

       total += square (5) + i;            

}

添加__attribute__((const))声明,编译器只调用了函数一次,以后只是直接得到了相同的一个返回值。

事实上,const参数不能用在带有指针类型参数的函数中,因为该属性不但影响函数的参数值,同样也影响到了参数指向的数据,它可能会对代码本身产生严重甚至是不可恢复的严重后果。并且,带有该属性的函数不能有任何副作用或者是静态的状态,类似getchar()或time()的函数是不适合使用该属性。

 

5. finstrument-functions

该参数可以使程序在编译时,在函数的入口和出口处生成instrumentation调用。恰好在函数入口之后并恰好在函数出口之前,将使用当前函数的地址和调用地址来调用下面的profiling函数。(在一些平台上,__builtin_return_address不能在超过当前函数范围之外正常工作,所以调用地址信息可能对profiling函数是无效的)

void  __cyg_profile_func_enter( void  *this_fn,void  *call_site );

void  __cyg_profile_func_exit( void  *this_fn,void  *call_site );

其中,第一个参数this_fn是当前函数的起始地址,可在符号表中找到;第二个参数call_site是调用处地址。

 

6. instrumentation

也可用于在其它函数中展开的内联函数。从概念上来说,profiling调用将指出在哪里进入和退出内联函数。这就意味着这种函数必须具有可寻址形式。如果函数包含内联,而所有使用到该函数的程序都要把该内联展开,这会额外地增加代码长度。如果要在C 代码中使用extern inline声明,必须提供这种函数的可寻址形式。
可对函数指定no_instrument_function属性,在这种情况下不会进行 instrumentation操作。例如,可以在以下情况下使用no_instrument_function属性:上面列出的profiling函数、高优先级的中断例程以及任何不能保证profiling正常调用的函数。

no_instrument_function

如果使用了-finstrument-functions,将在绝大多数用户编译的函数的入口和出口点调用profiling函数。使用该属性,将不进行instrument操作。

 

7. constructor/destructor

若函数被设定为constructor属性,则该函数会在main()函数执行之前被自动的执行。类似的,若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。拥有此类属性的函数经常隐式的用在程序的初始化数据方面,这两个属性还没有在面向对象C中实现。

 

8. 同时使用多个属性

可以在同一个函数声明里使用多个__attribute__,并且实际应用中这种情况是十分常见的。使用方式上,你可以选择两个单独的__attribute__,或者把它们写在一起,可以参考下面的例子:

extern void  die(const char *format, ...)   __attribute__( (noreturn))   __attribute__((format(printf, 1, 2)) );

或者写成

extern void  die(const char *format,...)    __attribute__( (noreturn,  format(printf, 1, 2)) );

如果带有该属性的自定义函数追加到库的头文件里,那么所以调用该函数的程序都要做相应的检查。

 

9. 和非GNU编译器的兼容性

__attribute__设计的非常巧妙,很容易作到和其它编译器保持兼容。也就是说,如果工作在其它的非GNU编译器上,可以很容易的忽略该属性。即使__attribute__使用了多个参数,也可以很容易的使用一对圆括弧进行处理,例如:

 /* 如果使用的是非GNU C, 那么就忽略__attribute__ */

#ifndef __GNUC__

      #define     __attribute__(x)     /* NOTHING * /

#endif

需要说明的是,__attribute__适用于函数的声明而不是函数的定义。所以,当需要使用该属性的函数时,必须在同一个文件里进行声明,例如:

/* 函数声明 */

void  die( const char *format, ... ) __attribute__( (noreturn) )   __attribute__( ( format(printf,1,2) ) );

void  die( const char *format,... )

{   /* 函数定义 */  }

更多属性参考:http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html

 

10. 变量属性(Variable Attributes)

关键字__attribute__也可以对变量(variable)或结构体成员(structure field)进行属性设置。

在使用__attribute__参数时,你也可以在参数的前后都加上“__”(两个下划线),例如,使用__aligned__而不是aligned,这样,你就可以在相应的头文件里使用它而不用关心头文件里是否有重名的宏定义。

 

11. 类型属性(Type Attribute)

关键字__attribute__也可以对结构体(struct)或共用体(union)进行属性设置。

大致有六个参数值可以被设定:aligned,packed,transparent_union,unused,deprecatedmay_alias

 

12. aligned (alignment)

该属性设定一个指定大小的对齐格式(以字节为单位),例如:

struct S { short f[3]; } __attribute__ ( ( aligned (8) ) );

typedef  int  more_aligned_int __attribute__ ( ( aligned (8) ) );

这里,如果sizeof(short)的大小为2(byte),那么,S的大小就为6。取一个2的次方值,使得该值大于等于6,则该值为8,所以编译器将设置S类型的对齐方式为8字节。该声明将强制编译器确保(尽它所能)变量类型为struct S或者more-aligned-int的变量在分配空间时采用8字节对齐方式。

如上所述,你可以手动指定对齐的格式,同样,你也可以使用默认的对齐方式。例如:

struct S { short f[3]; } __attribute__ ( (aligned) );

上面,aligned后面不紧跟一个指定的数字值,编译器将依据你的目标机器情况使用最大最有益的对齐方式。

int  x __attribute__ ( (aligned (16) ) )  =  0;

编译器将以16字节(注意是字节byte不是位bit)对齐的方式分配一个变量。也可以对结构体成员变量设置该属性,例如,创建一个双字对齐的int对,可以这么写:

Struct  foo {  int  x[2] __attribute__ ( (aligned (8) ) );  };

选择针对目标机器最大的对齐方式,可以提高拷贝操作的效率。
aligned属性使被设置的对象占用更多的空间,相反的,使用packed可以减小对象占用的空间。
需要注意的是,attribute属性的效力与你的连接器也有关,如果你的连接器最大只支持16字节对齐,那么你此时定义32字节对齐也是无济于事的。

 

13. packed

使用该属性可以使得变量或者结构体成员使用最小的对齐方式,即对变量是一字节对齐,对域(field)是位对齐。使用该属性对struct或者union类型进行定义,设定其类型的每一个变量的内存约束。当用在enum类型定义时,暗示了应该使用最小完整的类型 (it indicates that the smallest integral type should be used)。

下面的例子中,x成员变量使用了该属性,则其值将紧放置在a的后面:

struct  test

{

      char  a;

      int  x[2] __attribute__ ((packed));

};

下面的例子中,my-packed-struct类型的变量数组中的值将会紧紧的靠在一起,但内部的成员变量s不会被“pack”,如果希望内部的成员变量也被packed,my-unpacked-struct也需要使用packed进行相应的约束。

struct my_packed_struct

{

        char  c;

        int  i;

        struct  my_unpacked_struct  s;

}__attribute__ ( (__packed__) );

其它可选的属性值还可以是:cleanup,common,nocommon,deprecated,mode,section,shared, tls_model,transparent_union,unused,vector_size,weak,dllimport,dlexport等。

更多详细参考:http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Variable-Attributes.html#Variable-Attributes

 

14. 变量属性与类型属性举例

下面的例子中使用__attribute__属性定义了一些结构体及其变量,并给出了输出结果和对结果的分析。
程序代码为:

struct  p

{

       int a;

       char b;

       char c;

}__attribute__( ( aligned(4) ) ) pp;

struct  q

{

       int a;

       char b;

       struct n qn;

       char c;

}__attribute__( ( aligned(8) ) ) qq;

int  main()

{

       printf("sizeof(int)=%d,sizeof(short)=%d,sizeof(char)=%d/n",sizeof(int),sizeof(short),sizeof(char));

       printf("pp=%d,qq=%d /n", sizeof(pp),sizeof(qq));

       return 0;

}

输出结果:

sizeof(int)=4,sizeof(short)=2,sizeof(char)=1

pp=8,qq=24

分析:

sizeof(pp):

sizeof(a)+ sizeof(b)+ sizeof(c)=4+1+1=6<2^3=8= sizeof(pp)

sizeof(qq):

sizeof(a)+ sizeof(b)=4+1=5

sizeof(qn)=8;

即qn是采用8字节对齐的,所以要在a,b后面添3个空余字节,然后才能存储qn,

4+1+(3)+8+1=17

因为qq采用的对齐是8字节对齐,所以qq的大小必定是8的整数倍,即qq的大小是一个比17大又是8的倍数的一个最小值,由此得到

17<2^4+8=24= sizeof(qq)

更详细的介绍见:http://gcc.gnu.org/

下面是一些便捷的连接:

GCC 4.0 Function Attributes 

GCC 4.0 Variable Attributes 

GCC 4.0 Type Attributes 

 

15. Ref

简单__attribute__介绍:http://www.unixwiz.net/techtips/gnu-c-attributes.html

详细__attribute__介绍:http://gcc.gnu.org/

 

offsetof与container_of宏[总结]

1、前言

  今天在看代码时,遇到offsetof和container_of两个宏,觉得很有意思,功能很强大。offsetof是用来判断结构体中成员的偏移位置,container_of宏用来根据成员的地址来获取结构体的地址。两个宏设计的很巧妙,值得学习。linux内核中有着两个宏的定义,并在链表结构中得到应用。不得不提一下linux内核中的链表,设计的如此之妙,只需要两个指针就搞定了。后续认真研究一下这个链表结构。

2、offsetof宏

  使用offsetof宏需要包含stddef.h头文件,实例可以参考:http://www.cplusplus.com/reference/cstddef/offsetof/

      offsetof宏的定义如下:

#define offsetof(type, member) (size_t)&(((type*)0)->member)

  巧妙之处在于将地址0强制转换为type类型的指针,从而定位到member在结构体中偏移位置。编译器认为0是一个有效的地址,从而认为0是type指针的起始地址。

3、container_of宏

  使用container_of宏需要包含linux/kernel.h头文件,container_of宏的定义如下所示:

#define container_of(ptr, type, member) ({ 
     const typeof( ((type *)0)->member ) *__mptr = (ptr); 
     (type *)( (char *)__mptr - offsetof(type,member) );})    

container_of宏分为两部分,

第一部分:const typeof( ((type *)0)->member ) *__mptr = (ptr);

通过typeof定义一个member指针类型的指针变量__mptr,(即__mptr是指向member类型的指针),并将__mptr赋值为ptr。

第二部分: (type *)( (char *)__mptr - offsetof(type,member) ),通过offsetof宏计算出member在type中的偏移,然后用member的实际地址__mptr减去偏移,得到type的起始地址,即指向type类型的指针。

第一部分的目的是为了将统一转换为member类型指针。

4、测试程序

复制代码
复制代码
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define NAME_STR_LEN  32
 5 
 6 #define offsetof(type, member) (size_t)&(((type*)0)->member)
 7 
 8 #define container_of(ptr, type, member) ({ 
 9         const typeof( ((type *)0)->member ) *__mptr = (ptr); 
10         (type *)( (char *)__mptr - offsetof(type,member) );})
11 
12 typedef struct student_info
13 {
14     int  id;
15     char name[NAME_STR_LEN];
16     int  age;
17 }student_info;
18 
19 
20 int main()
21 {
22     size_t off_set = 0;
23     off_set = offsetof(student_info, id);
24     printf("id offset: %u
",off_set);
25     off_set = offsetof(student_info, name);
26     printf("name offset: %u
",off_set);
27     off_set = offsetof(student_info, age);
28     printf("age offset: %u
",off_set);
29     student_info *stu = (student_info *)malloc(sizeof(student_info));
30     stu->age = 10;
31     student_info *ptr = container_of(&(stu->age), student_info, age);
32     printf("age:%d
", ptr->age);
33     printf("stu address:%p
", stu);
34     printf("ptr address:%p
", ptr);
35     return 0;
36 }
复制代码
复制代码

测试结果:

5、参考网址

http://blog.csdn.net/thomas_nuaa/article/details/3542572

http://blog.chinaunix.net/uid-28489159-id-3549971.html

C语言中offsetof宏的应用

offsetof  :
    Retrieves the offset of a member from the beginning of its parent structure.

size_t offsetof(structName, memberName);

Parameters:
    structName : Name of the parent data structure.
    memberName :Name of the member in the parent data structure for which to determine the offset.

Return Value : offsetof returns the offset in bytes of the specified member from 
          the beginning of its parent data structure. It is undefined for bit fields.
Remarks :
    The offsetof macro returns the offset in bytes of memberName from the beginning of the structure specified by structName. You can specify types with the struct keyword.

Note  :
    offsetof is not a function and cannot be described using a C prototype.

 #define offsetof(s, m)   (size_t)&(((s *)0)->m)

s是一个结构名,它有一个名为m的成员(s和m 是宏offsetof的形参,它实际是返回结构s的成员m的偏移地址.

(s *)0 是骗编译器说有一个指向类(或结构)s的指针,其地址值0 

&((s *)0)->m   是要取得类s中成员变量m的地址. 因基址为0,这时m的地址当然就是m在s中的偏移

最后转换size_t 型,即unsigned int。

有例子如: 
struct   A 

    int   i; 
    int   j; 
}; 
   
struct   A   *pA; 
pA = new   A; 
这时,pA实际上是一个Pointer, 指向某一确定的内存地址, 如0x1234; 
而pA->i 整体是一个int型变量,其地址是&(pA->i), '&'为取址运算符; 
那么&(pA->i)一定等于0x1234,因 i 是结构体A的第一个元素。 
而&(pA->j)一定是0x1234 + 0x4 = 0x1238; 因为sizeof(int) = 4; 
   
这个做法的巧妙之处就是:它把“0”作为上例中的pA,那么&(pA->j)就是 j 的offset 

解析结果是: 
(s*)0,将 0 强制转换为Pointer to "s"    
可以记 pS = (s*)0,pS是指向s的指针,它的值是0; 
那么pS->m就是m这个元素了,而&(pS->m)就是m的地址,就是offset

下面是个offsetof应用的例子,其中宏OBJECT_HEAD_ADDRES的作用是根据一个对象或结构的某成员的地址,求其首地址。

完整的例子如下:

/* offsetof example */

#include "stdafx.h"
#include <stdio.h>
#include <stddef.h>

/************************************************************************/
/* Macro OBJECT_HEAD_ADDRESS : calculate the struct's address according
/* to one of its member's address
/************************************************************************/
#define OBJECT_HEAD_ADDRESS(ClassName,MemberName,Addre) /
Addre - offsetof(ClassName, MemberName)

struct S
{
int ID;
char *addr;
char name[20];
};

struct S1
{
S employee;
char *title;
};

struct S2
{
char singlechar;
int arraymember[10];
char anotherchar;
};

int main(int argc, char* argv[])
{
/* Example 1 
S2 s2 = {'a', 10, 'b'};
int head = int(&(s2.singlechar));
int memb = int(&(s2.anotherchar));

int i = OBJECT_HEAD_ADDRESS(S2, anotherchar, memb);

printf ("offsetof(S2, singlechar) is %d/n", offsetof(S2, singlechar));
printf ("offsetof(S2, arraymember) is %d/n", offsetof(S2, arraymember));
printf ("offsetof(S2, anotherchar) is %d/n", offsetof(S2, anotherchar));
printf("s2.anotherchar's address is %x ==> s2's address is %x/n", memb, i);
*/
/* Example 2 
S s = {100, "Nanjing", "Thomas"};
int id = int(&(s.ID));
int ad = int(&(s.addr));
int nm = int(&(s.name));

int j = OBJECT_HEAD_ADDRESS(S, addr, ad);

printf ("offsetof(S, ID) is %d/n", offsetof(S, ID));
printf ("offsetof(S, addr) is %d/n", offsetof(S, addr));
printf ("offsetof(S, name) is %d/n", offsetof(S, name));
printf ("s.ID's address : %x/ns.addr's address : %x/ns.name's address : %x/n", id, ad, nm);
printf("s.addr's address is %x ==> s's address is %x/n", ad, j);
*/
/* Example 3 */
S1 s1 = {{100, "Nanjing", "Thomas Chen"},"Thomas Chen"};
int td = int(&(s1.title));
int k = OBJECT_HEAD_ADDRESS(S1, title, td);

printf ("offsetof(S1, employee) is %d/n", offsetof(S1, employee));
printf ("offsetof(S1, title) is %d/n", offsetof(S1, title));
printf("s1.title's address is %x ==> s1's address is %x/n", td, k);

return 0;
}
/* Example 1 Output */
offsetof(S2, singlechar) is 0
offsetof(S2, arraymember) is 4
offsetof(S2, anotherchar) is 44
s2.anotherchar's address is 12ff7c ==> s2's address is 12ff50

/* Example 2 Output */
offsetof(S, ID) is 0
offsetof(S, addr) is 4
offsetof(S, name) is 8
s.ID's address : 12ff64
s.addr's address : 12ff68
s.name's address : 12ff6c
s.addr's address is 12ff68 ==> s's address is 12ff64

/* Example 3 Output */
offsetof(S1, employee) is 0
offsetof(S1, title) is 28
s1.title's address is 12ff7c ==> s1's address is 12ff60

Linux内核container_of详解

在开发Linux驱动的时候,经常会用到container_of这个宏:
include/linux/kernel.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  1. /**
  2.  * container_of - 通过结构体的一个成员获取容器结构体的指针
  3.  * @ptr: 指向成员的指针。
  4.  * @type: 成员所嵌入的容器结构体类型。
  5.  * @member: 结构体中的成员名。
  6.  *
  7.  */
  8. #define container_of(ptr, type, member) ({ 
  9.     const typeof( ((type *)0)->member ) *__mptr = (ptr); 
  10.     (type *)( (char *)__mptr - offsetof(type,member) );})
 
    这个宏的作用其实很简单,就是通过一个容器(结构体)中某个成员的指针得到指向这个容器(结构体)的指针,简单的说就是通过成员找容器。
 
这个宏的实现代码也就只有两行,下面仔细分析一下:
(1)const typeof( ((type *)0)->member ) *__mptr = (ptr);
定义一个中间变量__mptr,它等于提供给宏的参数ptr,也就是指向某个成员的指针。这个中间变量的命名意义是:
"__"代表内部使用,内核编程中常常这么做;
“m”代表middle。
 
 
(2)(type *)( (char *)__mptr - offsetof(type,member) );
这行代码的作用是通过中间变量__mptr(指向某个成员的指针)减去这个成员在容器(结构体)中的偏移来得到指向容器(结构体)的指针。
这里注意偏移的获取offsetof宏的实现:
 
include/linux/stddef.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  1. #ifdef __compiler_offsetof
  2. #define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
  3. #else
  4. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
  5. #endif
    这个实现依赖编译器,如果编译器内建了__compiler_offsetof(TYPE,MEMBER)的实现,就使用编译器的实现,否则就是用((size_t) &((TYPE *)0)->MEMBER)。
    在Linux-2.6.29(含)以上内核必须使用4.1.1(不含)以上的编译器,所以Linux-3.0内核肯定是使用了编译器内核内建的宏实现
 
include/linux/compiler-gcc4.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  1. #define __compiler_offsetof(a,b) __builtin_offsetof(a,b)
---------------------------------------------------------------------
宏分析完了,这里附上一个图来加深下印象:
 
红色代表输出,蓝色代表输入,黑色代表中间变量
原文地址:https://www.cnblogs.com/xiangtingshen/p/11002663.html