在C ++中为OSX创建共享库 [英] Creating shared libraries in C++ for OSX

查看:107
本文介绍了在C ++中为OSX创建共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在C ++中编程,我意识到我一直要重复编写相同的代码(主要是效用函数)。

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).

所以,我试图创建一个共享库并安装在PATH中,以便我可以使用的效用函数,当我需要。

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.

这是我做了到目前为止: -

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

使用以下内容创建文件 utils.h : -

Create a file utils.h with the following contents :-

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

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

Create a file utils.cpp with the following contents :-

#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;
}

按照以下步骤操作:
http://www.techytalk.info/c-cplusplus-library-programming- on-linux-part-two-dynamic-libraries /


  • 创建库对象代码: g ++ -Wall -fPIC -c utils.cpp

  • Create the library object code : g++ -Wall -fPIC -c utils.cpp

但是由于上面的链接是Linux的在OSX上不工作。有人建议阅读资源或建议提示如何在OSX机器上的路径中编译和设置这些对象?

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?

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

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?

推荐答案

使用 -dynamiclib OS X上的动态库:

Use -dynamiclib option to compile a dynamic library on OS X:

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

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

And then use it in your client application:

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

这篇关于在C ++中为OSX创建共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆