[C语言]__attribute__

本文详细介绍了C语言中的__attribute__特性,包括构造函数、内存对齐、紧凑结构、弱符号和弱引用的用法。通过实例展示了如何在程序中利用这些特性来优化代码执行和内存管理。了解这些技巧对于提升C语言编程效率和程序质量至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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函数。

链接

attribute((constructor))

Keil 字节对齐

C语言__attribute__的使用

C语言强、弱符号,强、弱引用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值