Linux 用 C++ 为 OSX 创建共享库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14173260/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:36:02  来源:igfitidea点击:

Creating shared libraries in C++ for OSX

c++linuxmacosstlshared-libraries

提问by

I just started programming in C++ and I've realized that I've been having to write the same code over and over again(mostly utility functions).

我刚开始用 C++ 编程,我意识到我不得不一遍又一遍地编写相同的代码(主要是实用程序函数)。

So, I'm trying to create a shared library and install it in PATH so that I could use the utility functions whenever I needed to.

因此,我正在尝试创建一个共享库并将其安装在 PATH 中,以便我可以在需要时使用实用程序函数。

Here's what I've done so far :-

这是我到目前为止所做的:-

Create a file utils.hwith the following contents :-

创建一个utils.h包含以下内容的文件:-

#include<iostream>
#include<string>
std::string to_binary(int x);

Create a file utils.cppwith the following contents :-

创建一个utils.cpp包含以下内容的文件:-

#include "utils.h"

std::string to_binary(int x) {
  std::string binary = "";
  while ( x > 0 ) {
    if ( x & 1 ) binary += "1";
    else binary += "0";
    x >>= 1;
  }
  return binary;
}

Follow the steps mentioned here :- http://www.techytalk.info/c-cplusplus-library-programming-on-linux-part-two-dynamic-libraries/

按照这里提到的步骤:- http://www.techytalk.info/c-cplusplus-library-programming-on-linux-part-two-dynamic-libraries/

  • Create the library object code : g++ -Wall -fPIC -c utils.cpp
  • 创建库对象代码: g++ -Wall -fPIC -c utils.cpp

But as the link above is meant for Linux it does not really work on OSX. Could someone suggest reading resources or suggest hints in how I could go about compiling and setting those objects in the path on an OSX machine?

但是由于上面的链接是针对 Linux 的,它在 OSX 上并不真正有效。有人可以建议阅读资源或建议我如何在 OSX 机器上的路径中编译和设置这些对象的提示吗?

Also, I'm guessing that there should be a way I can make this cross-platform(i.e. write a set of instructions(bash script) or a Makefile) so that I could use to compile this easily across platforms. Any hints on that?

另外,我猜应该有一种方法可以使这个跨平台(即编写一组指令(bash 脚本)或 Makefile),以便我可以轻松地跨平台编译它。任何提示?

采纳答案by linuxbuild

Use -dynamicliboption to compile a dynamic library on OS X:

使用-dynamiclib选项在 OS X 上编译动态库:

g++ -dynamiclib -o libutils.dylib utils.cpp

And then use it in your client application:

然后在您的客户端应用程序中使用它:

g++ client.cpp -L/dir/ -lutils

回答by spartygw

The link you posted is using C and the C compiler. Since you are building C++:

您发布的链接使用 C 和 C 编译器。由于您正在构建 C++:

g++ -shared -o libYourLibraryName.so utils.o