gcc 中的__attribute__

链接:

gcc attribute
gnu gcc attribute

__attribute__是gcc的关键字,它被视为一种语言的延伸。它可以帮助编译器优化调用,更仔细地检查代码的正确性,控制内存放置和代码生成选项。

语法:

__attribute__ ((attribute-list))

属性类别:

attribute((visibility(“default”))) :

一般来说动态库的符号都是隐藏的,除非强制声明。

创建vis.c源文件,not_hidden() 可以被发现,is_hidden() 被隐藏。其内容如下:

#include<stdio.h>
#include<stdlib.h>

__attribute ((visibility("default"))) void not_hidden ()
{
	printf("exported symbol/n");
}

void is_hidden ()
{
	printf("hidden one/n");
}

使用-fvisibility,编译成一个动态库:

gcc -shared -o libvis.so -fvisibility=hidden vis.c

编译结果:

(base) root@e9b213d41038:/home/work/usb/testdir# readelf -s libvis.so | grep hidden
     9: 000000000000061a    24 FUNC    GLOBAL DEFAULT   12 not_hidden
    37: 0000000000000632    24 FUNC    LOCAL  DEFAULT   12 is_hidden
    51: 000000000000061a    24 FUNC    GLOBAL DEFAULT   12 not_hidden

可以看到,属性确实有作用了。

现在编译源文件,main.c内容如下:

int main()
{
	not_hidden();
	is_hidden();
	return 0;
}

试图编译成一个可执行文件,链接到刚才生成的动态库,

(base) root@e9b213d41038:/home/work/usb/testdir# gcc -o exe main.c -L ./ -lvis
main.c: In function 'main':
main.c:3:3: warning: implicit declaration of function 'not_hidden' [-Wimplicit-function-declaration]
   not_hidden();
   ^~~~~~~~~~
main.c:4:3: warning: implicit declaration of function 'is_hidden' [-Wimplicit-function-declaration]
   is_hidden();
   ^~~~~~~~~
/tmp/ccKfpoSS.o: In function `main':
main.c:(.text+0x14): undefined reference to `is_hidden'
collect2: error: ld returned 1 exit status

修改如下,没有报错:

int main()
{
	not_hidden();
	//is_hidden();
	return 0;
}

说明了 attribute((visibility(“default”))) 为隐式声明。

__attribute__((visibility("default")))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值