简体   繁体   English

在Windows和LINUX中创建程序库[C ++]

[英]Creating program libraries in Windows and LINUX [C++]

I am planning to use libraries in my C++ program. 我打算在我的C ++程序中使用库。 Development is happening on Linux but application is designed to compile on both Linux and Windows. 开发正在Linux上进行,但应用程序旨在在Linux和Windows上进行编译。 I understand direct equivalent for shared libraries(.so) in windows is DLL, right? 据我所知,Windows中共享库(.so)的直接等价物是DLL,对吧?

In Linux using g++, I can create shared library using -fPIC and -shared flags. 在使用g ++的Linux中,我可以使用-fPIC-shared标志创建共享库。 AFAIK, there is no other code change required for a shared library. AFAIK,共享库不需要进行其他代码更改。 But things are different in a Windows DLL. 但是Windows DLL中的情况有所不同。 There I should specify the functions which have to be exported using dllexport , right? 在那里我应该指定必须使用dllexport导出的函数,对吧?

My question is how do I manage this situation? 我的问题是如何处理这种情况? I mean dllexport is invalid in Linux and the compiler will give an error. 我的意思是dllexport在Linux中无效,编译器会出错。 But it is required in Windows. 但它在Windows中是必需的。 So how do I write a function which will compile on both platforms without any code change? 那么如何编写一个可以在两个平台上编译而无需更改代码的函数呢?

Compilers used 使用的编译器

  • g++ - LINUX g ++ - LINUX
  • VC++ - Windows VC ++ - Windows

Any help would be great! 任何帮助都会很棒!

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. 然后,您可以检查平台,只在Windows上定义宏。 Eg: 例如:

#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代码中的字符串。

Another alternative is to just use a .def file for your windows project. 另一种方法是只为Windows项目使用.def文件。 This file specifies the DLL exports, so you won't have to mess up your code base. 此文件指定DLL导出,因此您不必弄乱代码库。 (But macros are definately the way to go if you want to avoid the extra file.) (但是如果你想避免额外的文件,宏肯定是要走的路。)

You can use #ifdef preprocessor directive for conditional compiling. 您可以使用#ifdef预处理程序指令进行条件编译。 For example: 例如:

#ifdef WIN32
    // Win32 specific code
#else
    // Elsewhere
#endif

Another option, one that I use now, is to use MinGW on Windows. 我现在使用的另一个选项是在Windows上使用MinGW This way you can use gcc on Windows, and you don't have to worry about the declspec nonsense. 这样你就可以在Windows上使用gcc了,你不必担心declspec废话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM