屏蔽静态库接口

分享屏蔽静态库接口的一种方法.

准备

hello.c:

#include <stdio.h>

__attribute__ ((visibility ("default"))) void hello() {
	printf("Hello World!\n");
}

hello.h:

#ifndef __HELLO__H
#define __HELLO__H

#ifdef __cplusplus
extern "C" {
#endif

void hello();

#ifdef __cplusplus
}
#endif

#endif

bye.c:

#include <stdio.h>

void bye() {
	printf("Bye Bye!\n");
}

bye.h:

#ifndef __BYE__H
#define __BYE__H

#ifdef __cplusplus
extern "C" {
#endif

void bye();

#ifdef __cplusplus
}
#endif

#endif

编译

编译时使用-fvisibility=hidden,可以默认将符号隐藏;需要对外的符号使用__attribute__ ((visibility ("default")))修饰即可:

$ gcc -fvisibility=hidden -I. -c hello.c -o hello.o
$ gcc -fvisibility=hidden -I. -c bye.c -o bye.o

其中hello()未被隐藏,bye()是被隐藏的.

链接

将生成的两个.o文件重定位到libt.o中:

$ ld -r hello.o bye.o -o libt.o

去除无用的符号

$ strip --strip-unneeded libt.o

隐藏的符号本地化(我也不知道中文怎么翻译了)

$ objcopy --localize-hidden libt.o libt_hidden.o

打包成静态库

$ ar crv libt.a libt_hidden.o

验证

调用未被隐藏的hello()

test1.c:

#include "hello.h"

int main(void) {
    hello();
    return 0;
}

编译并运行

$ gcc -I. test1.c -L. -lt -o test
$ ./test
Hello World!

调用隐藏的bye()

test2.c

#include "bye.h"

int main(void) {
    bye();
    return 0;
}

编译并运行

$ gcc -I. test2.c -L. -lt -o test
$ ./test
/tmp/ccdaJT7s.o: In function `main':
test2.c:(.text+0xa): undefined reference to `bye'
collect2: error: ld returned 1 exit status

微信公众号同步更新,微信搜索"AnSwEr不是答案"或者扫描二维码,即可订阅。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值