c++ - 如何使用在 DLL 上定义的全局 const 变量
问题描述
我有下一个文件common/const.h:
#ifndef COMMON_CONST_H
#define COMMON_CONST_H
#if defined _WIN32 || defined _WIN64
#ifdef PCOM_EXPORTS
#define PCOM_WINAPI __declspec(dllexport)
#else
#define PCOM_WINAPI __declspec(dllimport)
#endif // PCOM_EXPORTS
#endif // _WIN32
namespace common {
extern PCOM_WINAPI const char DIR_SEPARATOR;
}
#endif /* COMMON_CONST_H */
和common/const.cpp:
#include "common/const.h"
namespace common {
#if defined _WIN32 || defined _WIN64
const char DIR_SEPARATOR = '\\';
#else
const char DIR_SEPARATOR = '/';
#endif
}
我生成它的 DLL 文件没有问题。但是当我想使用另一个库中的这个DIR_SEPARATOR变量时,我得到:
Util.obj:错误 LNK2001:未解析的外部符号“char const common::DIR_SEPARATOR”:致命错误 LNK1120:1 个未解析的外部符号
Util.cpp(dll客户端)代码是:
#include "common/const.h"
...
namespace db {
...
shared_ptr<iptree> Util::loadIniFile(const string& filePath) {
string file = filePath;
replace(file.begin(), file.end(), '/', prompt::common::DIR_SEPARATOR);
shared_ptr<iptree> tree(new iptree);
...
}
}
我的问题是:
- 如果我在 Util.cpp 中包含 common/const.h ( ),为什么会得到未解析的外部符号“char const common::DIR_SEPARATOR”
namespace common { extern PCOM_WINAPI const char DIR_SEPARATOR; }
? - 所有这些代码都在 Linux 上完美运行(.so 由客户端生成和使用)。为什么将它移植到 Windows 时出现此错误?Visual Studio 2017 默认使用 C++14 作为标准。在 Linux 上,我使用 C++11。dll 项目和客户端项目具有相同的配置。所以我几乎可以肯定问题不在这里。
- 我需要做什么才能使用这些代码?
我只想设置一次DIR_SEPARATOR值。这种情况下可以吗?我错过了什么吗?
提前致谢。
解决方案
推荐阅读
- php - PHP Mysql 搜索页面
- python - 解决此错误的任何方法,在行中:“std=float(line)-average ValueError: could not convert string to float”
- html - 扩展身高css
- fabricjs - 创建后无法选择线对象
- .net - VB.Net - 如果程序停止,appendAllText 子例程是否可以不写入所有文本?
- python - 我想打印带有奇数或偶数的字母(字符串)作为索引并将它们保存为列表
- scala - 如何将混合类型列表转换为相同类型列表的元组
- java - java中的主线程会调用静态块吗?
- scala - 是否可以在匹配情况下使用隐式函数?
- angular - 由于设备 Ionic 上的访问控制检查,XMLHttpRequest 无法加载 XXXX