文章目录
attribute
attribute_ 语法格式为:attribute ((attribute-list))
1、__attribute__((constructor))//在main函数之前,先执行一个函数
static __attribute__((constructor(101))) void before1();//101表示优先级,如果有多个constructor的话,1~100为系统预留。优先级可以不写
2、__attribute__ ((aligned))
struct S {
short b[3];
} __attribute__ ((aligned (8))); //分配空间采用8字节对齐
//如果aligned 后面不紧跟一个指定的数字值,那么编译器将依据你的目标机器情况使用最大最有益的对齐方式。
//还可以---使用#pragma pack (value)时的指定对齐值value
3、__attribute__ ((packed))
struct packed_struct
{
char c;
int i;
struct unpacked_struct s;
}__attribute__ ((__packed__));
//成员内存分配采用紧凑模式,但是成员的成员不会采用紧凑,除非成员本身就是紧凑的
4、__attribute__((weak))
//弱符号(或弱定义) weak属性只会在静态库(.o .a )中生效,动态库(.so)中不会生效
例子:
test.h
#ifndef __RUO__
#define __RUO__
void test_func();
endif
test.c
#include<stdio.h>
void __attribute__((weak)) test_func()
{
printf("weak func---\n");
}
main.c
#include<stdio.h>
#include"test.h"
void test_func()
{
printf("strong func---\n");
}
int main()
{
test_func();
return 0;
}
结果: strong func—; 若不在main.c定义test_func则输出弱定义的函数内容
强定义存在则使用强定义,不存在则使用弱定义
5、__attribute__((weakref(“别名”)))
//弱引用,必须是static类型,别名要写,不然等效于weak(其实也可以直接写成weak的形式)。
例子:
test.h
#ifndef __YIN__
#define __YIN__
void test_func();
#endif
test.c
#include<stdio.h>
static __atrribute__((weakref(test))) void weak_ref();
void test_func()
{
if(weak_ref)
weak_ref();
else
printf("the weak_ref is null---\n");
}
main.c
#include<stdio.h>
#include"test.h"
void test()
{
printf("strong func---\n");
}
int main()
{
test_func();
return 0;
}
结果:strong func—;若不定义test函数,则输出"the…null—"。
因为是静态声明,这个函数名的作用域被限定在本模块内,所以即使是我们在其他模块中定义了weak_ref函数,也无法影响到当前模块中的weak_ref函数。