动态链接库之dllexport和__attribute__(visibility)

在实际的应用中,我们需要动态库导出特定的符号(有些接口不对外暴露,只内部使用),下面的例子展示了具体的实现方式。

1. code
//log.h
#pragma once

#define BUILDING_DLL

#if defined _WIN32 || defined __CYGWIN__
#ifdef BUILDING_DLL
#ifdef __GNUC__
#define DLL_PUBLIC __attribute__ ((dllexport))
#else
#define DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
#endif
#else
#ifdef __GNUC__
#define DLL_PUBLIC __attribute__ ((dllimport))
#else
#define DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
#endif
#endif
#define DLL_LOCAL
#else
#if __GNUC__ >= 4
#define DLL_PUBLIC __attribute__ ((visibility ("default")))
#define DLL_LOCAL  __attribute__ ((visibility ("hidden")))
#else
#define DLL_PUBLIC
#define DLL_LOCAL
#endif
#endif

#include <iostream>

extern "C" DLL_PUBLIC void  Log(std::string msg);

DLL_LOCAL void Log_local(std::string msg);

DLL_PUBLIC void Version(void);
//log.cpp
#include "log.h"

void Log(std::string msg) {
	std::cout << "Log: " << msg << '\n';
}

void Log_local(std::string msg) {
	std::cout << "local Log: " << msg << '\n';
}

void Version(void) {
	std::cout << "V 0.0.1" << '\n';
}

上述代码中,LogVersion是对外的接口,而同时,Log利用extern "C"避免了C++的名字混淆。

2. msvc

将上述代码在vs2019中生成dll,利用命令查看其导出的符号,

msvc

从上图可以看出,LogVersion是对外的接口,同时Version由于名字混淆,变得不太可读。

gcc

将上述代码在linux gcc下生成so,在编译时,可以添加gcc编译选项,

-fvisibility=hidden

因为我用的Cmake,所以也可以,

set(CMAKE_CXX_VISIBILITY_PRESET hidden)

利用命令查看其导出的符号,

gcc

从图中可以看出,对外导出的接口为LogVersion,同时Version进行了名字混淆。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值