简体   繁体   English

在C ++ for OSX中创建共享库

[英]Creating shared libraries in C++ for OSX

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.h with the following contents :- 使用以下内容创建文件utils.h : -

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

Create a file utils.cpp with 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. 但由于上面的链接适用于Linux,因此它并不适用于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? 有人建议阅读资源或建议我如何在OSX机器上的路径中编译和设置这些对象吗?

Also, I'm guessing that there should be a way I can make this cross-platform(ie write a set of instructions(bash script) or a Makefile) so that I could use to compile this easily across platforms. 此外,我猜测应该有一种方法可以使这个跨平台(即编写一组指令(bash脚本)或Makefile),以便我可以使用它跨平台轻松编译。 Any hints on that? 有什么提示吗?

Use -dynamiclib option 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

The link you posted is using C and the C compiler. 您发布的链接是使用C和C编译器。 Since you are building C++: 因为您正在构建C ++:

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

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

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