在 Windows 和 LINUX 中创建程序库 [C++]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/967930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating program libraries in Windows and LINUX [C++]
提问by Navaneeth K N
I am planning to use libraries in my C++ program. Development is happening on Linux but application is designed to compile on both Linux and Windows. I understand direct equivalent for shared libraries(.so) in windows is DLL, right?
我计划在我的 C++ 程序中使用库。开发是在 Linux 上进行的,但应用程序旨在在 Linux 和 Windows 上编译。我理解 Windows 中共享库 (.so) 的直接等价物是 DLL,对吗?
In Linux using g++, I can create shared library using -fPIC
and -shared
flags. AFAIK, there is no other code change required for a shared library. But things are different in a Windows DLL. There I should specify the functions which have to be exported using dllexport, right?
在使用 g++ 的 Linux 中,我可以使用-fPIC
和-shared
标志创建共享库。AFAIK,共享库不需要其他代码更改。但是在 Windows DLL 中情况有所不同。在那里我应该指定必须使用dllexport导出的函数,对吗?
My question is how do I manage this situation? I mean dllexportis invalid in Linux and the compiler will give an error. But it is required in Windows. So how do I write a function which will compile on both platforms without any code change?
我的问题是我该如何处理这种情况?我的意思是dllexport在 Linux 中无效,编译器会报错。但它在 Windows 中是必需的。那么我如何编写一个可以在两个平台上编译而无需任何代码更改的函数呢?
Compilers used
使用的编译器
- g++ - LINUX
- VC++ - Windows
- g++ - LINUX
- VC++ - 视窗
Any help would be great!
任何帮助都会很棒!
回答by stefanB
We specify __declspec(dllexport)
for class:
我们__declspec(dllexport)
为类指定:
#define EXPORT_XX __declspec(dllexport)
class EXPORT_XX A
{
};
You can then check for platform and only define the macro on windows. E.g.:
然后您可以检查平台并仅在 Windows 上定义宏。例如:
#ifdef WIN32
#define EXPORT_XX __declspec(dllexport)
#else
#define EXPORT_XX
#endif
We mostly build static libraries so there might be more stuff to do for dynamic libs but the concept is the same - use preprocessor macro to define string that you need to insert into Windows code.
我们主要构建静态库,因此动态库可能需要做更多的事情,但概念是相同的 - 使用预处理器宏来定义需要插入到 Windows 代码中的字符串。
回答by Peter Ruderman
Another alternative is to just use a .def file for your windows project. This file specifies the DLL exports, so you won't have to mess up your code base. (But macros are definately the way to go if you want to avoid the extra file.)
另一种选择是只为您的 Windows 项目使用 .def 文件。此文件指定 DLL 导出,因此您不必弄乱您的代码库。(但如果你想避免额外的文件,宏绝对是要走的路。)
回答by Alan Haggai Alavi
You can use #ifdef
preprocessor directive for conditional compiling. For example:
您可以使用#ifdef
预处理器指令进行条件编译。例如:
#ifdef WIN32
// Win32 specific code
#else
// Elsewhere
#endif